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

相关文章

Java设计模式---迭代器模式(Iterator)解读

《Java设计模式---迭代器模式(Iterator)解读》:本文主要介绍Java设计模式---迭代器模式(Iterator),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录1、迭代器(Iterator)1.1、结构1.2、常用方法1.3、本质1、解耦集合与遍历逻辑2、统一

Java内存分配与JVM参数详解(推荐)

《Java内存分配与JVM参数详解(推荐)》本文详解JVM内存结构与参数调整,涵盖堆分代、元空间、GC选择及优化策略,帮助开发者提升性能、避免内存泄漏,本文给大家介绍Java内存分配与JVM参数详解,... 目录引言JVM内存结构JVM参数概述堆内存分配年轻代与老年代调整堆内存大小调整年轻代与老年代比例元空

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

Java 线程安全与 volatile与单例模式问题及解决方案

《Java线程安全与volatile与单例模式问题及解决方案》文章主要讲解线程安全问题的五个成因(调度随机、变量修改、非原子操作、内存可见性、指令重排序)及解决方案,强调使用volatile关键字... 目录什么是线程安全线程安全问题的产生与解决方案线程的调度是随机的多个线程对同一个变量进行修改线程的修改操

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

从原理到实战深入理解Java 断言assert

《从原理到实战深入理解Java断言assert》本文深入解析Java断言机制,涵盖语法、工作原理、启用方式及与异常的区别,推荐用于开发阶段的条件检查与状态验证,并强调生产环境应使用参数验证工具类替代... 目录深入理解 Java 断言(assert):从原理到实战引言:为什么需要断言?一、断言基础1.1 语

深度解析Java项目中包和包之间的联系

《深度解析Java项目中包和包之间的联系》文章浏览阅读850次,点赞13次,收藏8次。本文详细介绍了Java分层架构中的几个关键包:DTO、Controller、Service和Mapper。_jav... 目录前言一、各大包1.DTO1.1、DTO的核心用途1.2. DTO与实体类(Entity)的区别1

Java中的雪花算法Snowflake解析与实践技巧

《Java中的雪花算法Snowflake解析与实践技巧》本文解析了雪花算法的原理、Java实现及生产实践,涵盖ID结构、位运算技巧、时钟回拨处理、WorkerId分配等关键点,并探讨了百度UidGen... 目录一、雪花算法核心原理1.1 算法起源1.2 ID结构详解1.3 核心特性二、Java实现解析2.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

mysql表操作与查询功能详解

《mysql表操作与查询功能详解》本文系统讲解MySQL表操作与查询,涵盖创建、修改、复制表语法,基本查询结构及WHERE、GROUPBY等子句,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随... 目录01.表的操作1.1表操作概览1.2创建表1.3修改表1.4复制表02.基本查询操作2.1 SE