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);
}
相关推荐
咖啡八杯5 小时前
GoF设计模式——策略模式
java·后端·spring·设计模式
lizhongxuan6 小时前
AI Agent 上下文压缩利器 Headroom
后端
Csvn8 小时前
SSH 远程管理与安全加固 — 运维的守门之道
后端
IT_陈寒8 小时前
Python搞不定字符串编码?这破玩意坑我两小时!
前端·人工智能·后端
菜鸟谢10 小时前
Rust 智能指针完整详解
后端
菜鸟谢10 小时前
Rust 函数完整知识点详解
后端
爱勇宝10 小时前
淡泊名利之前,先承认我们都很焦虑
前端·后端·程序员
菜鸟谢10 小时前
Rust 闭包(Closure)完整详解
后端
ServBay10 小时前
如何利用本地技术栈构建 0 成本 AI SaaS 雏形
后端·aigc·ai编程
菜鸟谢10 小时前
Rust 集合 + 迭代器完整详解
后端