(九)、SpringBoot + Security RememberMe(记住我)功能

可以前往第一篇博客查看目录结构 --> 这里

一、修改application.properties文件,添加数据库配置

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/zeke-demo
spring.datasource.username=root
spring.datasource.password=

二、修改zeke-login.html,添加记住我勾选框

        <tr>
            <td colspan="2"><input type="checkbox" name="remember-me" value="true">记住我</td>
        </tr>

三、在BrowserProperties类中添加 rememberMeSeconds属性和对应的getter、setter方法

    private int rememberMeSeconds = 3600;

四、修改BrowserSecurityConfig,注入一个Bean

    @Autowired
    private DataSource dataSource;

    /**
     * 记住我功能
     * @return
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //自动创建数据库表,使用一次后注释掉,不然会报错
//        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

五、修改configure(HttpSecurity http)方法

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
        validateCodeFilter.setAuthenticationFailureHandler(zekeAuthenticationFailureHandler);
        validateCodeFilter.setSecurityProperties(securityProperties);
        validateCodeFilter.afterPropertiesSet();

        http.csrf().disable();
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class);
        http.formLogin() //表单登录
                .loginPage("/authentication/require") //用户未登录时的处理地址
                .loginProcessingUrl("/authentication/form") //用户登录
                .successHandler(zekeAuthenticationSuccessHandler) //登录成功处理
                .failureHandler(zekeAuthenticationFailureHandler) //登录失败处理
                .and()
                .rememberMe()
                .tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSeconds())
                .userDetailsService(userDetailsService)
                .and()
                .authorizeRequests()
                .antMatchers("/authentication/require",
                        securityProperties.getBrowser().getLoginPage(),
                        "/code/image") //不拦截的URL
                .permitAll()
                .anyRequest()
                .authenticated();
    }

六、启动服务,访问localhost/zeke-login.html,勾选记住我测试

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值