spring security的记住我实现

在上一篇博客中,在自定义的配置类中,增加数据源的注入,增加一个PersistentTokenRepository 的Bean

@Autowired
    private DataSource dataSource;

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        // 第一次启动的时候自动创建表,其他时候注释掉
        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

关于为什么是这个Bean类,需要底层了解源码原理
在这里插入图片描述

记住我的功能,一方面把cookie保存在浏览器客户端,同时也把用户登录信息存入了数据库,在有效期类实现自动登录。
在重写方法中增加配置时长

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login.html") // 设置登录页面地址
                .loginProcessingUrl("/test/login") // 设置登录页处理地址form 表单的action地址,路径随意,这个配置配合上面的登录地址
               // .successForwardUrl("/success.html") // 设置成功跳转地址
               // .failureUrl("/error.html") // 设置失败跳转地址
                .defaultSuccessUrl("/test/default")
               // .usernameParameter("uname") // 表单不是username
              //  .passwordParameter("pword") // 表单不是password
                .permitAll() // 设置默认成功跳转页面
                .and().authorizeRequests().antMatchers("/","/test/login").permitAll()// 设置不用认证的地址
                //.antMatchers("/test/index").hasAuthority("add")
                //.antMatchers("/test/index").hasAnyAuthority("add,delete")
                //.antMatchers("/test/index").hasRole("sale")
                //.antMatchers("/test/index").hasAnyRole("sale")
                .anyRequest().authenticated() //其他请求需要认证授权
                .and().rememberMe()
                .tokenValiditySeconds(60) // 设置记住我的时间,单位秒
                .tokenRepository(persistentTokenRepository).userDetailsService(myUserDetailsService)
                .and().csrf().disable(); // 关闭csrf防护

        // 自定义403错误页面
        http.exceptionHandling().accessDeniedPage("/error.html");
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/index").permitAll();
    }

可以看到自动创建了表
在这里插入图片描述
在自定义的登录页面添加一个name为remember-me的CheckBox,这样就实现了记住我的功能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄宝康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值