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);
}
相关推荐
花间相见18 小时前
【Java基础面试题】—— 核心知识点面试题(含答案):语法+集合+JVM+设计模式+算法
java·jvm·设计模式
钟智强19 小时前
从2.7GB到481MB:我的Docker Compose优化实战,以及为什么不能全信AI
后端·docker
会飞De琥珀19 小时前
java工具类,字符串转时间
java·开发语言
曹牧19 小时前
JSON 数组的正确使用方式
java·服务器·前端
LINgZone219 小时前
深入解析:Cglib与JDK动态代理的实现原理、区别及性能对比
java·开发语言
华科易迅19 小时前
Spring JDBC
java·后端·spring
云烟成雨TD19 小时前
Spring AI 1.x 系列【17】函数型工具开发与使用
java·人工智能·spring
小村儿19 小时前
一起吃透 Claude Code,告别 AI 编程迷茫
前端·后端·ai编程
程序员大飞哥19 小时前
云控SLA的数学:250ms端到端延迟预算怎么分配给传输层
后端
云烟成雨TD20 小时前
Spring AI 1.x 系列【15】AI Agent 基石:Tool Calling 标准与 Spring AI 集成
java·人工智能·spring