Spring Security自动登录笔记

一、Spring Security思想


红色代表第一次登录自动保存token的流程

蓝色代表关闭浏览器后第二次访问token的查找以及数据比对的流程

二、实现自动登录

1、在配置类中配置PersistentTokenRepository决定token数据的处理方式

    //1、配置数据源
    @Autowired
    private DataSource dataSource;
    //配置PersistentTokenRepository,该类用于配置token数据的处理方式
    //1、JdbcTokenRepositoryImpl 将token数据持久化(通过数据保存token)
    //2、InMemoryTokenRepositoryImpl 将token数据存在内存中
    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
    
    
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        //配置数据源
        jdbcTokenRepository.setDataSource(dataSource);
        //自动生成存储token的表
        //jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

2、配置WebSecurityConfigurerAdapter的实现方法configure(HttpSecurity httpSecurity)

    public void configure(HttpSecurity httpSecurity) throws Exception {
    
    
//        httpSecurity.exceptionHandling().accessDeniedPage("/403");   /* 配置没有权限访问条状自定义页面 */
        //用户登录
        ....
                //权限设置
                ....
                //token配置
                .and().rememberMe().tokenRepository(persistentTokenRepository())    /* 2、设置PersistentTokenRepository */
                .tokenValiditySeconds(60)   /* 设置有效时长,单位秒 */
                .userDetailsService(userDetailsService)
                .and().csrf().disable();     /* 关闭csrf防护 */
        //用户注销
        ....

    }

3前端页面设置checkbox并将其name属性设置为remember-me

<body>
    <h1>my login page</h1>
    <!-- action要与配置中的登录访问路径一致 -->
    <form action="/user/login" method="post">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <!-- 设置checkbox 的name为 remember-me -->
        <input type="checkbox" name="remember-me">自动登录<br>
        <input type="submit" value="login">
    </form>
</body>

4、运行效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/magicproblem/article/details/112647325