Notas de inicio de sesión automático de Spring Security

Uno, pensó Spring Security


El rojo representa el proceso de guardar tokens automáticamente al iniciar sesión por primera vez

El azul representa el proceso de búsqueda de tokens y comparación de datos para la segunda visita después de cerrar el navegador.

En segundo lugar, realice el inicio de sesión automático

1. Configure PersistentTokenRepository en la clase de configuración para determinar cómo se procesan los datos del 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. Configure el método de implementación de 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 Establezca la casilla de verificación en la página de inicio y establezca su atributo de nombre para recordarme

<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. Efecto de la operación

Inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/magicproblem/article/details/112647325
Recomendado
Clasificación