Spring Security 中实现 Remember Me 记住密码功能

2024-09-05 09:58

本文主要是介绍Spring Security 中实现 Remember Me 记住密码功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在 Spring Boot 应用中使用 Spring Security 并实现 Remember Me 记住密码功能,实现自动登录
项目地址 https://github.com/helloworlde/SpringSecurity


前置条件:在 Spring Boot 应用中已正确配置 Spring Security

##在页面添加记住密码的复选框

 <input type="checkbox" name="remember-me"/> Remember me

##在 Security Config 配置文件中启用记住密码功能(验证信息存放在内存中)

  • SecurityConfig
    import cn.com.hellowood.springsecurity.security.CustomAuthenticationProvider;import cn.com.hellowood.springsecurity.security.CustomUserDetailsService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdater;@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate CustomAuthenticationProvider customAuthenticationProvider;@Autowiredprivate CustomUserDetailsService userDetailsService;@Overrideprotected void configure(HttpSecurity http) throws Exception {// 任何用户都可以访问以下URIhttp.authorizeRequests().antMatchers("/", "/login", "/login-error", "/css/**", "/index").permitAll();// 其他URI均需要权限校验http.authorizeRequests().anyRequest().authenticated();// 只需要以下配置即可启用记住密码http.authorizeRequests().and().rememberMe();http.formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password").successForwardUrl("/user/index").failureUrl("/login-error");}@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) {// 为了使用用户名密码校验实现了AuthenticationProvider和UserDetailsService类auth.authenticationProvider(customAuthenticationProvider);try {auth.userDetailsService(userDetailsService);} catch (Exception e) {e.printStackTrace();}}}

这样就可以使用记住密码了,选择记住密码登录后会在本地保存 Cookie,下次登录的时候通过 Cookie 校验用户信息;用户登录的信息保存在内存中,当内存断电或被清除之后该 Cookie 即使在有效期内也无法登录。


通过数据库存放校验信息实现记住密码登录

###创建保存校验信息的表(表名和字段值必须为以下内容)

    CREATE TABLE persistent_logins (username  VARCHAR(64) NOT NULL,series    VARCHAR(64) NOT NULL PRIMARY KEY,token     VARCHAR(64) NOT NULL,last_used TIMESTAMP   NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP);

配置 Security Config

    import cn.com.hellowood.springsecurity.security.*;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.Bean;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.core.session.SessionRegistry;import org.springframework.security.core.session.SessionRegistryImpl;import org.springframework.security.web.authentication.RememberMeServices;import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;import javax.sql.DataSource;@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {private final Logger logger = LoggerFactory.getLogger(getClass());@Autowiredprivate CustomAuthenticationProvider customAuthenticationProvider;@Autowiredprivate CustomUserDetailsService userDetailsService;// 数据源是为了JdbcRememberMeImpl实例而注入的,如果不设置数据源会在登陆的时候抛空指针异常@Autowired@Qualifier("dataSource")DataSource dataSource;@Overrideprotected void configure(HttpSecurity http) throws Exception {// 任何用户都可以访问以下URIhttp.authorizeRequests().antMatchers("/", "/login", "/login-error", "/css/**", "/index").permitAll();// 其他URI需要权限验证http.authorizeRequests().anyRequest().authenticated();// 当通过JDBC方式记住密码时必须设置 key,key 可以为任意非空(null 或 "")字符串,但必须和 RememberMeService 构造参数的// key 一致,否则会导致通过记住密码登录失败http.authorizeRequests().and().rememberMe().rememberMeServices(rememberMeServices()).key("INTERNAL_SECRET_KEY");// 当登录成功后会被重定向到 /user/index, 所以 loginPage 和 loginProcessingUrl 相同http.formLogin().loginPage("/login").loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password").successForwardUrl("/user/index").failureUrl("/login-error");}/*** 返回 RememberMeServices 实例** @return the remember me services*/@Beanpublic RememberMeServices rememberMeServices() {JdbcTokenRepositoryImpl rememberMeTokenRepository = new JdbcTokenRepositoryImpl();// 此处需要设置数据源,否则无法从数据库查询验证信息rememberMeTokenRepository.setDataSource(dataSource);// 此处的 key 可以为任意非空值(null 或 ""),单必须和起前面// rememberMeServices(RememberMeServices rememberMeServices).key(key)的值相同PersistentTokenBasedRememberMeServices rememberMeServices =new PersistentTokenBasedRememberMeServices("INTERNAL_SECRET_KEY", userDetailsService, rememberMeTokenRepository);// 该参数不是必须的,默认值为 "remember-me", 但如果设置必须和页面复选框的 name 一致rememberMeServices.setParameter("remember-me");return rememberMeServices;}/*** Configure global.** @param auth the auth* @throws Exception the exception*/@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) {// 为了使用用户名密码校验实现了AuthenticationProvider和UserDetailsService类auth.authenticationProvider(customAuthenticationProvider);try {auth.userDetailsService(userDetailsService);} catch (Exception e) {logger.error("Set userDetailService failed, {}", e.getMessage());e.printStackTrace();}}}

这样就可以实现将校验信息保存在数据库中,下次通过记住密码登录后再次访问页面会根据 Cookie 查找该用户的登录信息,如果登录信息有效则登录成功, 否则重定向到登录页面


  • 自定义实现 AuthenticationProvider 接口
    import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.authentication.AuthenticationProvider;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;import org.springframework.security.core.GrantedAuthority;import org.springframework.stereotype.Component;import java.util.ArrayList;import java.util.List;/*** The type Custom authentication provider.** @author HelloWood*/@Componentpublic class CustomAuthenticationProvider implements AuthenticationProvider {private final Logger logger = LoggerFactory.getLogger(getClass());@Autowiredprivate CustomUserDetailsService userDetailsService;/*** Validate user info is correct form database** @param authentication* @return* @throws AuthenticationException*/@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {String username = authentication.getName();String password = authentication.getCredentials().toString();List<GrantedAuthority> grantedAuthorities = new ArrayList<>();logger.info("start validate user {} login", username);// 通过用户名和密码校验,如果校验不通过会抛出 AuthenticationExceptionuserDetailsService.loadUserByUsernameAndPassword(username, password);Authentication auth = new UsernamePasswordAuthenticationToken(username, password, grantedAuthorities);return auth;}@Overridepublic boolean supports(Class<?> authentication) {return authentication.equals(UsernamePasswordAuthenticationToken.class);}}
  • 自定义实现 UserDetailsService 接口
import cn.com.hellowood.springsecurity.mapper.UserMapper;import cn.com.hellowood.springsecurity.model.UserModel;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.authentication.AccountExpiredException;import org.springframework.security.authentication.BadCredentialsException;import org.springframework.security.core.AuthenticationException;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;import javax.servlet.http.HttpSession;import java.util.ArrayList;/*** The type Custom user details service.** @author HelloWood*/@Service("userDetailsService")public class CustomUserDetailsService implements UserDetailsService {private Logger logger = LoggerFactory.getLogger(getClass());@Autowiredprivate UserMapper userMapper;@Autowiredprivate HttpSession session;/*** 通过用户名和密码加载用户信息并校验** @param username the username* @param password the password* @return the user model* @throws AuthenticationException the authentication exception*/public UserModel loadUserByUsernameAndPassword(String username, String password) throws AuthenticationException {logger.info("user {} is login by username and password", username);UserModel user = userMapper.getUserByUsernameAndPassword(username, password);validateUser(username, user);return user;}/*** 通过用户名加载用户信息,重写该方法用于记住密码后通过 Cookie 登录* * @param username* @param user*/@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {logger.info("user {} is login by remember me cookie", username);UserModel user = userMapper.getUserByUsername(username);validateUser(username, user);return new User(user.getUsername(), user.getPassword(), new ArrayList<GrantedAuthority>());}/*** 校验用户信息并将用户信息放在 Session 中** @param username* @param user*/private void validateUser(String username, UserModel user) {if (user == null) {logger.error("user {} login failed, username or password is wrong", username);throw new BadCredentialsException("Username or password is not correct");} else if (!user.getEnabled()) {logger.error("user {} login failed, this account had expired", username);throw new AccountExpiredException("Account had expired");}// TODO There should add more logic to determine locked, expired and others statuslogger.info("user {} login success", username);// 当用户信息有效时放入 Session 中session.setAttribute("user", user);}}

这篇关于Spring Security 中实现 Remember Me 记住密码功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1138641

相关文章

golang 对象池sync.Pool的实现

《golang对象池sync.Pool的实现》:本文主要介绍golang对象池sync.Pool的实现,用于缓存和复用临时对象,以减少内存分配和垃圾回收的压力,下面就来介绍一下,感兴趣的可以了解... 目录sync.Pool的用法原理sync.Pool 的使用示例sync.Pool 的使用场景注意sync.

IDEA实现回退提交的git代码(四种常见场景)

《IDEA实现回退提交的git代码(四种常见场景)》:本文主要介绍IDEA实现回退提交的git代码(四种常见场景),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.已提交commit,还未push到远端(Undo Commit)2.已提交commit并push到

Kotlin Compose Button 实现长按监听并实现动画效果(完整代码)

《KotlinComposeButton实现长按监听并实现动画效果(完整代码)》想要实现长按按钮开始录音,松开发送的功能,因此为了实现这些功能就需要自己写一个Button来解决问题,下面小编给大... 目录Button 实现原理1. Surface 的作用(关键)2. InteractionSource3.

java对接第三方接口的三种实现方式

《java对接第三方接口的三种实现方式》:本文主要介绍java对接第三方接口的三种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录HttpURLConnection调用方法CloseableHttpClient调用RestTemplate调用总结在日常工作

golang中slice扩容的具体实现

《golang中slice扩容的具体实现》Go语言中的切片扩容机制是Go运行时的一个关键部分,它确保切片在动态增加元素时能够高效地管理内存,本文主要介绍了golang中slice扩容的具体实现,感兴趣... 目录1. 切片扩容的触发append 函数的实现2. runtime.growslice 函数gro

golang实现动态路由的项目实践

《golang实现动态路由的项目实践》本文主要介绍了golang实现动态路由项目实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习... 目录一、动态路由1.结构体(数据库的定义)2.预加载preload3.添加关联的方法一、动态路由1

使用Python实现调用API获取图片存储到本地的方法

《使用Python实现调用API获取图片存储到本地的方法》开发一个自动化工具,用于从JSON数据源中提取图像ID,通过调用指定API获取未经压缩的原始图像文件,并确保下载结果与Postman等工具直接... 目录使用python实现调用API获取图片存储到本地1、项目概述2、核心功能3、环境准备4、代码实现

MySQL数据库实现批量表分区完整示例

《MySQL数据库实现批量表分区完整示例》通俗地讲表分区是将一大表,根据条件分割成若干个小表,:本文主要介绍MySQL数据库实现批量表分区的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考... 目录一、表分区条件二、常规表和分区表的区别三、表分区的创建四、将既有表转换分区表脚本五、批量转换表为分区

Spring 缓存在项目中的使用详解

《Spring缓存在项目中的使用详解》Spring缓存机制,Cache接口为缓存的组件规范定义,包扩缓存的各种操作(添加缓存、删除缓存、修改缓存等),本文给大家介绍Spring缓存在项目中的使用... 目录1.Spring 缓存机制介绍2.Spring 缓存用到的概念Ⅰ.两个接口Ⅱ.三个注解(方法层次)Ⅲ.

Spring Boot 整合 Redis 实现数据缓存案例详解

《SpringBoot整合Redis实现数据缓存案例详解》Springboot缓存,默认使用的是ConcurrentMap的方式来实现的,然而我们在项目中并不会这么使用,本文介绍SpringB... 目录1.添加 Maven 依赖2.配置Redis属性3.创建 redisCacheManager4.使用Sp