spring 用户通过交互界面登录成功事件源码分析

版本

spring-security-web:5.6.7

源码

用户通过前端交互界面登录成功触发此事件

org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent

事件触发过程

  • 用户名密码认证过滤器
    org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
java 复制代码
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter 
  • 认证处理过滤器
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter
java 复制代码
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
	throws IOException, ServletException {
	if (!requiresAuthentication(request, response)) {
		chain.doFilter(request, response);
		return;
	}
	try {
		// 尝试对请求进行认证
		Authentication authenticationResult = attemptAuthentication(request, response);
		if (authenticationResult == null) {
			return;
		}
		this.sessionStrategy.onAuthentication(authenticationResult, request, response);
		// 认证成功
		if (this.continueChainBeforeSuccessfulAuthentication) {
			chain.doFilter(request, response);
		}
		successfulAuthentication(request, response, chain, authenticationResult);
	}
	catch (InternalAuthenticationServiceException failed) {
		this.logger.error("An internal error occurred while trying to authenticate the user.", failed);
		unsuccessfulAuthentication(request, response, failed);
	}
	catch (AuthenticationException ex) {
		// Authentication failed
		unsuccessfulAuthentication(request, response, ex);
	}
}
// 默认的认证成功处理行为
// 1. 将认证对象设置到安全上下文
// 2. 通知RememberMe服务
// 3. 发布交互认证成功事件
// 4. 执行成功处理器
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
	Authentication authResult) throws IOException, ServletException {
	SecurityContext context = SecurityContextHolder.createEmptyContext();
	context.setAuthentication(authResult);
	SecurityContextHolder.setContext(context);
	if (this.logger.isDebugEnabled()) {
		this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authResult));
	}
	this.rememberMeServices.loginSuccess(request, response, authResult);
	if (this.eventPublisher != null) {
		this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
	}
	this.successHandler.onAuthenticationSuccess(request, response, authResult);
}
相关推荐
XS03010613 分钟前
Spring框架
java·后端·spring
Rabitebla18 分钟前
C++ 内存管理全面复习:从内存分布到 operator new/delete
java·c语言·开发语言·c++·算法·leetcode
xcLeigh19 分钟前
Go入门:main包与main函数的特殊地位
开发语言·后端·golang
Darren2451 小时前
JWT、OAuth 2.0 与 SSO 详解
后端
我是人✓1 小时前
SQL主键与外键
java·数据库
SelectDB1 小时前
Apache Doris / SelectDB 实时分析三大范式:技术能力、选型对比与企业实践
后端
圣光SG1 小时前
Java操作题练习(二)
java·开发语言·python
蜡台1 小时前
Android WebView 设计指南
android·java·kotlin
SelectDB1 小时前
Apache Doris 向量化执行与 CPU 性能优化:技术能力、选型对比与实践
后端
CoderLiu1 小时前
Agent 工程的下一层:为什么「把流程写成图」还不够,还需要 Graph Engineering
前端·人工智能·后端