Spring Security账户与密码验证实现过程

 更新时间:2023年03月28日 08:27:42   作者:T.Y.Bao  
这篇文章主要介绍了Spring Security账户与密码验证实现过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧

这里使用Spring Boot 2.7.4版本,对应Spring Security 5.7.3版本

本文样例代码地址: spring-security-oauth2.0-sample

关于Username/Password认证的基本流程和基本方法参见官网 Username/Password Authentication

Introduction

Username/Password认证主要就是Spring Security 在 HttpServletRequest中读取用户登录提交的信息的认证机制。

Spring Security提供了登录页面,是前后端不分离的形式,前后端分离时的配置需另加配置。本文基于前后端分离模式来叙述。

基本流程如下:

Username/Password认证可分为两部分:

  • 从HttpServletRequest中获取用户登录信息
  • 从密码存储处获取密码并比较

关于获取获取用户登录信息,Spring Security支持三种方式(基本用的都是Form表单提交,即POST方式提交):

  • Form
  • Basic
  • Digest

关于密码的获取和比对,关注下面几个类和接口:

  • UsernamePasswordAuthenticationFilter: 过滤器,父类AbstractAuthenticationProcessingFilter中组合了AuthenticationManagerAuthenticationManager的默认实现ProviderManager中又组合了多个AuthenticationProvider,该接口实现类,有一个DaoAuthenticationProvider负责获取用户密码以及权限信息,DaoAuthenticationProvider又把责任推卸给了UserDetailService
  • PasswordEncoder : 密码加密方式
  • UserDetails : 代表用户,包括 用户名、密码、权限等信息
  • UserDetailsService : 最终实际调用获取 UserDetails的接口,通常用户实现。

整个流程的UML图如下:

前后端分离模式下配置

先来看对SecurityFilterChain的配置:

@Configuration
@EnableMethodSecurity()
@RequiredArgsConstructor
public class SecurityConfig {
	// 自定义成功处理,主要存储登录信息并返回jwt
	private final LoginSuccessHandler loginSuccessHandler;
	// 自定义失败处理,返回json格式而非默认的html
    private final LoginFailureHandler loginFailureHandler;
    private final CustomSessionAuthenticationStrategy customSessionAuthenticationStrategy;
	...
	@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    	// 设置登录成功后session处理, 认证成功后
        // SessionAuthenticationStrategy的最早执行,详见AbstractAuthenticationProcessingFilter
        // 执行顺序:
        // 1. SessionAuthenticationStrategy#onAuthentication
        // 2. SecurityContextHolder#setContext
        // 3. SecurityContextRepository#saveContext
        // 4. RememberMeServices#loginSuccess
        // 5. ApplicationEventPublisher#publishEvent
        // 6. AuthenticationSuccessHandler#onAuthenticationSuccess
        http.sessionManagement().sessionAuthenticationStrategy(customSessionAuthenticationStrategy);
		...
		// 前后端不分离,可指定html返回。该项未测试
        // http.formLogin().loginPage("login").loginProcessingUrl("/hello/login");
        // 前后端分离下username/password登录
        http.formLogin()
                .usernameParameter("userId")
                .passwordParameter("password")
                // 前端登陆页面对这个url提交username/password即可
                // 必须为Post请求,且Body格式为x-www-form-urlencoded,如果要接受application/json格式,需另加配置
                .loginProcessingUrl("/hello/login")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler);
                //  .securityContextRepository(...)  // pass
       ...
       return http.build();
	}
	...
}

使用Postman测试:

登录成功登陆失败

AbstractAuthenticationProcessingFilter

该类是UsernamePasswordAuthenticationFilterOAuth2LoginAuthenticationFilter的父类,使用模板模式构建。

UsernamePasswordAuthenticationFilter只负责从HttpServletRequest中获取用户提交的用户名密码,而真正去认证、事件发布、SessionAuthenticationStrategy、AuthenticationSuccessHandler、AuthenticationFailureHandler、SecurityContextRepository、RememberMeServices这些内容均组合在AbstractAuthenticationProcessingFilter中。

public abstract class AbstractAuthenticationProcessingFilter extends GenericFilterBean
		implements ApplicationEventPublisherAware, MessageSourceAware {
	...
	// 委托给子类ProviderManager执行认证,最终由DaoAuthenticationProvider认证
	// DaoAuthenticationProvider中会调用UserDetailsService#loadUserByUsername(username)接口方法
	// 我们只需实现该UserDetailsService接口注入Bean容器即可
	private AuthenticationManager authenticationManager;
	private SessionAuthenticationStrategy sessionStrategy;
	protected ApplicationEventPublisher eventPublisher;
	private RememberMeServices rememberMeServices;
	private AuthenticationSuccessHandler successHandler;
	private AuthenticationFailureHandler failureHandler;
	private SecurityContextRepository securityContextRepository;
	...
	private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		...
		try {
			// 模板模式,该方法子类实现
			Authentication authenticationResult = attemptAuthentication(request, response);
			// 1. 	
			this.sessionStrategy.onAuthentication(authenticationResult, request, response);
			// Authentication success
			if (this.continueChainBeforeSuccessfulAuthentication) {
				chain.doFilter(request, response);
			}
			// 成功后续处理
			successfulAuthentication(request, response, chain, authenticationResult);
		}
		catch (InternalAuthenticationServiceException failed) {
			// 失败后续处理
			unsuccessfulAuthentication(request, response, failed);
		}
		catch (AuthenticationException ex) {
			// Authentication failed
			unsuccessfulAuthentication(request, response, ex);
		}
	}
	// 模板模式,由UsernamePasswordAuthenticationFilter完成
	public abstract Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException;}
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
			Authentication authResult) throws IOException, ServletException {
		SecurityContext context = SecurityContextHolder.createEmptyContext();
		context.setAuthentication(authResult);
		// 2. 
		SecurityContextHolder.setContext(context);
		// 3. 
		this.securityContextRepository.saveContext(context, request, response);
		// 4.
		this.rememberMeServices.loginSuccess(request, response, authResult);
		if (this.eventPublisher != null) {
			// 5.
			this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
		}
		// 6.
		this.successHandler.onAuthenticationSuccess(request, response, authResult);
	}
}

UsernamePasswordAuthenticationFilter

public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		if (this.postOnly && !request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}
		String username = obtainUsername(request);
		username = (username != null) ? username.trim() : "";
		String password = obtainPassword(request);
		password = (password != null) ? password : "";
		UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
				password);
		// Allow subclasses to set the "details" property
		setDetails(request, authRequest);
		// 调用父类中字段去认证,最终是 UserDetailService#loadUserByUsername(String username),该接口实现类由程序员根据业务定义。
		return this.getAuthenticationManager().authenticate(authRequest);
	}
	// ************** 重要 **************
	// 这里只能通过x-www-urlencoded方式获取,如果前端传过来application/json,是解析不到的
	// 非要用application/json,建议重写UsernamePasswordAuthenticationFilter方法,但由于body中内容默认只能读一次,又要做很多其他配置,比较麻烦,建议这里x-www-urlencoded
	// *********************************
	@Nullable
	protected String obtainUsername(HttpServletRequest request) {
		return request.getParameter(this.usernameParameter);
	}
	@Nullable
	protected String obtainPassword(HttpServletRequest request) {
		return request.getParameter(this.passwordParameter);
	}
}

到此这篇关于Spring Security账户与密码验证实现过程的文章就介绍到这了,更多相关Spring Security内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 基于SpringMVC实现网页登录拦截

    基于SpringMVC实现网页登录拦截

    SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。因此,本文将为大家介绍如何通过SpringMVC实现网页登录拦截功能,需要的小伙伴可以了解一下
    2021-12-12
  • Junit写法及与spring整合过程详解

    Junit写法及与spring整合过程详解

    这篇文章主要介绍了Junit写法及与spring整合过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • SpringBoot中HTTP请求不通的原因级解决方法

    SpringBoot中HTTP请求不通的原因级解决方法

    HTTP 请求是指从客户端到服务器的请求消息,对于一个 Spring Boot 项目而言,服务器就是 Spring Boot,客户端就是用户本地的浏览器,但是会遇到SpringBoot HTTP请求不通的问题,本文介绍了一些常见问题及解决方法,需要的朋友可以参考下
    2025-02-02
  • Java中Iterator(迭代器)的用法详解

    Java中Iterator(迭代器)的用法详解

    Java迭代器(Iterator)是 Java 集合框架中的一种机制,它提供了一种在不暴露集合内部实现的情况下遍历集合元素的方法。本文主要介绍了它的使用方法,希望对大家有所帮助
    2023-05-05
  • Java 基础语法中的逻辑控制

    Java 基础语法中的逻辑控制

    这篇文章主要介绍了Java 基础语法中的逻辑控制的相关资料,需要的朋友可以参考下面文章内容
    2021-09-09
  • Java多线程处理千万级数据更新操作

    Java多线程处理千万级数据更新操作

    这篇文章主要为大家详细介绍了Java如何通过多线程处理千万级数据更新操作,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-11-11
  • Java中final关键字的深入探究

    Java中final关键字的深入探究

    这篇文章主要给大家介绍了关于Java中final关键字的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Java具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-06-06
  • Java实现超简单抖音去水印的示例详解

    Java实现超简单抖音去水印的示例详解

    抖音去水印方法很简单,以前一直没有去研究,以为搞个去水印还要用到算法去除,直到动手的时候才发现这么简单,不用编程基础都能做。所以本文将介绍一个超简单抖音视频去水印方法,需要的可以参考一下
    2022-03-03
  • Java基础之Filter的实例详解

    Java基础之Filter的实例详解

    这篇文章主要介绍了Java基础之Filter的实例详解的相关资料,需要的朋友可以参考下
    2017-07-07
  • 一文详解Java中的AuthRequest类(附Demo)

    一文详解Java中的AuthRequest类(附Demo)

    公共接口,定义了对第三方平台进行授权、登录、撤销授权和刷新 token 的操作,本文将详细分析Java中的AuthRequest类(附Demo),文中通过代码示例介绍的非常详细,具有一定的参考价值,需要的朋友可以参考下
    2024-04-04

最新评论