SpringSecurity(十四)—RememberMe功能实现

SpringSecurity(十四)—RememberMe功能实现

一.使用理由

Spring Security 中Remember Me为“记住我”功能,用户只需要在登录时添加remember-me复选框,取值为true。Spring Security会自动把用户信息存储到数据源中,以后就可以不登录进行访问。

二.实现步骤

1.添加依赖(jdbc和mysql)

Spring Security实现Remember Me 功能时底层实现依赖Spring-JDBC,所以需要添加jdbc的依赖,如果使用的是mybatis框架,只要导入mybatis的启动器即可,同时还需添加mysql的驱动

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

2.配置数据源

在application.properties或application.yml中配置数据源。请确保数据库中已经存在test数据库

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?useSSL=false
    username: root
    password: admin

3.编写配置

新建com.yrp.config.RememberMeConfig类,并创建Bean对象

@Configuration
public class RememberMeConfig {
   
    @Autowired
    private DataSource dataSource;
    @Bean
    public PersistentTokenRepository getPersistentTokenRepository(){
   
        JdbcTokenRepositoryImpl jdbcTokenRepository=new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //自动建表,第一次启动时需要,第二次启动时注释掉
        //jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;

    }
}

4.修改SecurityConfig

在SecurityConfig中添加PersistentTokenRepository和UserDetailsService实现类对象,并自动注入。
在configure中添加下面配置内容。

  @Autowired
  private MyAuthImpl myAuth;
  @Autowired
  private PersistentTokenRepository getPersistentTokenRepository;
     //加入rememberMe的功能
        http.rememberMe()
                .userDetailsService(myAuth)
                .tokenRepository(getPersistentTokenRepository)
        

5.在客户端页面中添加复选框

<form action = "/login" method="post">
    用户名:<input type="text" name="username"/><br/>
    密码:<input type="text" name="password"/><br/>
 记住我:   <input type="checkbox" name="remember-me" value="true"/> <br/>
    <input type="submit" value="登录"/>
</form>

6.有效时间

默认2周时间。但是可以通过设置状态有效时间,即使项目重新启动下次也可以正常登录。

//remember Me
http.rememberMe()
        .tokenValiditySeconds(120)//单位:秒
        .tokenRepository(repository)
        .userDetailsService(userDetailsServiceImpl);
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/2350.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号