Sping boot Oauth2.0 添加记住我功能

现在各种系统的登入页面一般都会有记住密码,记住我的功能。在使用oauth的时候,framework本身就提供了相关功能。我们只需要简单的配置一下就可以使用了。


1.首先登入页面添加一个checkbox

  <input type="checkbox" value="true" name="remember-me">记住我

checkbox的name定义在 org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer
类定义的代码片段:

public final class RememberMeConfigurer> extends AbstractHttpConfigurer, H> {
    private static final String DEFAULT_REMEMBER_ME_NAME = "remember-me";
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    private String key;
    private RememberMeServices rememberMeServices;
    private LogoutHandler logoutHandler;
    private String rememberMeParameter = "remember-me";
    private String rememberMeCookieName = "remember-me";
    private String rememberMeCookieDomain;
    private PersistentTokenRepository tokenRepository;
    private UserDetailsService userDetailsService;
    private Integer tokenValiditySeconds;
    private Boolean useSecureCookie;
    private Boolean alwaysRemember;

2.后端开启记住我的功能

@Configuration
@EnableWebSecurity
@Order(SecurityProperties.BASIC_AUTH_ORDER)
public class ServerSecurityConfiguration extends WebSecurityConfigurerAdapter {
 
    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        // org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer.tokenRepository
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        // 该对象里面有定义创建表的语句
        // 可以设置让该类来创建表
        // 但是该功能只用使用一次,如果数据库已经存在表则会报错
        //jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

    // UserDetailsService的实现类
    @Resource
    UserServiceImpl userService;
    
    // 数据源配置
    @Resource
    private DataSource dataSource;

    @Override
    protected void configure(final HttpSecurity http) throws Exception {

        ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
        validateCodeFilter.setFailureHandler(myAuthenticationFailureHandler);

        http
                .....(省略一大堆配置)
                and().
                rememberMe()
                .tokenRepository(persistentTokenRepository)
                // 新增过期配置,单位秒,默认配置写的60秒
                .tokenValiditySeconds(60 * 60 * 24 * 7)
                .userDetailsService(userService);
    }
}

开启记住我功能后,登入成功时,会多一个名为remember-me的cookie,服务器会将相关数据写入数据库持久化保存。

暂无评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.