【SpringSecurity系列】SpringBoot集成SpringSecurity添加记住我的功能

从一篇文章里我们已经添加了验证码进行登录,这篇博文,我们将添加一个新的功能记住我的来进行登录,防止需要反复去登录,提高用户体验。

首先我们来看一下具体的流程图:

【SpringSecurity系列】SpringBoot集成SpringSecurity添加记住我的功能_第1张图片

当我们第一次登录的认证通过UsernamePasswordAuthenticationFilter链接器后,我们会进入RemeberMeService,这个方法主要做两个操作,一个是将我们的认证token写入数据库,一个是将token写入浏览器的Cookie中。当我们再次调用请求的时候,RememberMeAuthenticationFilter拦截器就会进行拦截判断读取我的token通过TokenRepository去数据库里进行查找,如果找到就返回我们之前封装好的UserDetailsService去拿用户信息,如果没有查找到,就抛出相应的异常。

下面就是代码实现,首先在我们的配置类里,添加进行数据库的链接的代码:

@Autowired
//进行操作的数据源
private DataSource dataSource; 

 @Autowired
 private CodeProperties codeProperties;

 @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
//        tokenRepository.setCreateTableOnStartup(true); 这个操作是帮我们自定创建一张表,只需操作一次,当数据库这张表已经存在的时候,会报错
        return tokenRepository;
    }

对于上面代码中我注掉的操作,其实我们可以进入JdbcTokenRepositoryImpl的源码中把,创建表的语句直接拿出来,我们进行手动的创建:

//源码中创建表的语句
create table persistent_logins (username varchar(64) not null, series varchar(64) primary key, token varchar(64) not null, last_used timestamp not null)

还需要配置我们的过期时间:

@Configuration
public class CodeProperties {

    private int rememberMeSeconds = 3600;

    public int getRememberMeSeconds() {
        return rememberMeSeconds;
    }

    public void setRememberMeSeconds(int rememberMeSeconds) {
        this.rememberMeSeconds = rememberMeSeconds;
    }
}

然后在我们的配置方法中加入我们rememberMe的配置:

 .and()
                .rememberMe()
                .tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(codeProperties.getRememberMeSeconds())
                .userDetailsService(userDetailsService)

这个就是添加记住我的操作,最后我们在页面上添加记住我的按钮:

表单登录

用户名:
密码:
图形验证码:
记住我

其中name属性的名字必须是“remember-me”,最后生成的页面就是这样:

【SpringSecurity系列】SpringBoot集成SpringSecurity添加记住我的功能_第2张图片

当我们第一次登录成功后,重启我们的服务器的时候,再次登录的时候,也不需要在跳转登录页面了!

完整项目代码请从git上拉取git地址

你可能感兴趣的:(SpringSecurity)