Spring Security之认证过滤器

news2024/9/23 9:26:44

前言

上回我们探讨了关于Spring Security,着实复杂。这次咱们聊的认证过滤器就先聊聊认证功能。涉及到多方协同的功能,咱分开聊。也给小伙伴喘口气,嘻嘻。此外也是因为只有登录认证了,才有后续的更多功能集成的可能。

认证过滤器

认证过滤器是Web应用中负责处理用户认证请求的。这意味着他要验证用户的身份,确认你是谁。只有确认用户身份后,才能授予对应的权限,才能在后续访问对应的受保护资源。因此,在我看来,认证过滤器实际上需要完成两个事情:

  • 确认用户身份。
  • 授权。例如,角色。

SpringSecurity没有“鉴权”这概念?

其实我认为前面说到的AuthorizationFilter应该叫鉴权过滤器,在识别用户身份后甄别用户是否具备访问权限。我刻意找了一下英文,Authentication可以认证、鉴定、身份验证的意思,Authorization可以是授权、批准的意思。第一眼,竟然有点懵逼。。没有上下文的情况下,Authentication可以是认证,也可以是鉴权。而Authorization可以是授权、也可以是鉴权(批准-访问)。

得,我一直以来的疑惑也找到了:为什么Spring Security里面没有“鉴权”相关概念,而只有认证、授权?如果放到Spring Security的语境中,Authentication就是认证的意思,而且还非常准确,因为他还有身份验证的意思。Authorization则是鉴权的含义,授权/批准你访问某个请求。如果非要区分开,则还应使用Identification作为认证这个概念最为合适。

实际上,SpringSecurity在获取用户信息的时候就已经把用户的完整信息包括权限也加载了,所以认证也包括了我们在聊纯概念的“授权”。而SpringSecurity的Authorization是“授权访问”,也就是“鉴权”。因此,可以说在SpringSecurity中只有“认证”和“鉴权”。因为他要求加载的用户信息是包括权限的,跟认证在一块了。别把“授权”概念跟RABC这些“授权方式”混为一谈了,鄙人就懵圈了好久。关于授权和认证不妨再回头看看之前的文章:Spring Security之认证与授权的概念

SpringSecurity支持认证方式

Spring Security支持多种认证方式:

认证方式过滤器SecurityConfigurer描述
基于Basic认证BasicAuthenticationFilterHttpBasicConfigurer原生支持,开箱即用
基于Digest认证DigestAuthenticationFilter无,需要自己引入原生支持,开箱即用
基于OAuth2认证-资源服务器BearerTokenAuthenticationFilterOAuth2ResourceServerConfigurer需要spring-boot-starter-oauth2-resource-server包
基于OAuth2认证-客户端OAuth2LoginAuthenticationFilterOAuth2LoginConfigurer需要spring-boot-starter-oauth2-resource-server包
基于OAuth2认证-客户端OAuth2AuthorizationCodeGrantFilterOAuth2ClientConfigurer需要spring-boot-starter-oauth2-resource-server包
基于CAS认证CasAuthenticationFilter本来是有Configurer的,4.0之后被弃用,再之后就移除了需要spring-security-cas包
基于第三方系统认证AbstractPreAuthenticatedProcessingFilter-用户在其他系统已经认证了,在当前系统通过RequestAttribute/Header/Cookie等等方式获取到用户名后直接再当前系统把用户信息读取出来。
基于用户名和密码认证UsernamePasswordAuthenticationFilterFormLoginConfigurer原生支持

PS: OAuth2比较复杂,有四种登录方式,还分客户端应用、用户、资源。后面有机会再细聊。

基于第三方系统认证的方式,也有几个原生的实现:
基于J2EE认证:J2eePreAuthenticatedProcessingFilter-JeeConfigurer
基于WebSphere: WebSpherePreAuthenticatedProcessingFilter
基于X509证书认证:X509AuthenticationFilter-X509Configurer
基于Header:RequestHeaderAuthenticationFilter
基于RequestAttribute:RequestAttributeAuthenticationFilter

以上就是Spring Security原生提供的支持、或者通过官方的jar包能够开箱即用的。

基于用户名和密码认证

好了,下面我们来重点关注一下基于用户名和密码的认证方式。首先我们来认识一些必要的核心组件:

组件作用备注
UserDetails提供用户信息,包括权限提供了默认实现:User
UserDetailsService用于加载装载用户信息在认证之前需要先根据用户名查询用户
AuthenticationManager负责完成认证逻辑实现类ProviderManager

前面两个比较容易理解,无非就是加载用户。而后者,对于ProviderManager而言,相较于我们之前基于方法进行权限配置的方式所使用AuthorizationManager来说,无异于单独开辟了一块新天地。

  • ProviderManager
    就名字而言,他就是基于AuthenticationProvider来完成。额,没错,他就是一个新的接口,也就是一个新的组件。而ProviderManager主要的作用就是,根据Authentication的类型,寻找匹配的AuthenticationProvider,然后调用匹配的AuthenticationProvider来完成认证。

核心代码:

public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean {
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		Class<? extends Authentication> toTest = authentication.getClass();
		Authentication result = null;
		Authentication parentResult = null;
		int size = this.providers.size();
		// 遍历所有的AuthenticationProvider 
		for (AuthenticationProvider provider : getProviders()) {
			if (!provider.supports(toTest)) {
				continue;
			}
			// 找到第一个能处理的AuthenticationProvider就执行authenticate
			result = provider.authenticate(authentication);
			if (result != null) {
				copyDetails(authentication, result);
				break;
			}
		}
		// 如果认证失败就尝试由父AuthenticationManager认证,这部代码省略了
		// 认证成功则返回结果
		// 处理异常-省略代码
	}
}

关于这个AuthenticationProvider,我们来感受一下他的实现:
AuthenticationProvider
之所以会有这么多,是因为Authentication有很多,每个用来表示凭证的都需要不同的处理,然后才能进行认证。例如:JwtAuthenticationToken需要将jwtToken解析后就能得到当前用户已经认证的用户信息了(OAuth2)。这些实现有不少是这种类似于token的。不过我们的用户名和密码方式,则是更为复杂。

public abstract class AbstractUserDetailsAuthenticationProvider
		implements AuthenticationProvider, InitializingBean, MessageSourceAware {
		
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		// 1. 获取用户名
		String username = determineUsername(authentication);
		// 2. 尝试从缓存中获取用户信息
		boolean cacheWasUsed = true;
		UserDetails user = this.userCache.getUserFromCache(username);
		if (user == null) {
			// 缓存中不存在,则加载用户:使用UserDetailsService
			user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
		}
		// 3. 进行认证:验证用户状态、验证用户凭证(密码)
		try {
			// 验证用户状态
			this.preAuthenticationChecks.check(user);
			// 验证用户凭证(密码)
			additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
		}
		catch (AuthenticationException ex) {
			// 重试
		}
		// 验证成功后,检查凭证有效期
		this.postAuthenticationChecks.check(user);
		if (!cacheWasUsed) {
			// 缓存用户
			this.userCache.putUserInCache(user);
		}
		Object principalToReturn = user;
		if (this.forcePrincipalAsString) {
			principalToReturn = user.getUsername();
		}
		// 创建UsernamePasswordAuthenticationToken
		return createSuccessAuthentication(principalToReturn, authentication, user);
	}	

	protected Authentication createSuccessAuthentication(Object principal, Authentication authentication,
			UserDetails user) {
		// 构建认证信息(已验证凭证),里面包含当前用户信息和权限
		UsernamePasswordAuthenticationToken result = UsernamePasswordAuthenticationToken.authenticated(principal,
				authentication.getCredentials(), this.authoritiesMapper.mapAuthorities(user.getAuthorities()));
		result.setDetails(authentication.getDetails());
		return result;
	}
}

public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

	@Override
	@SuppressWarnings("deprecation")
	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
		if (authentication.getCredentials() == null) {
			// 没有凭证
			throw new BadCredentialsException(this.messages
				.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
		}
		String presentedPassword = authentication.getCredentials().toString();
		// 校验密码
		if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
			throw new BadCredentialsException(this.messages
				.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
		}
	}
}

现在我们知道用户是怎么完成认证的,还有很重要的一环:认证成功之后,用户信息怎么保存?我们都知道一般保存在Session中。

UsernamePasswordAuthenticationFilter

其核心实现在父类:

public abstract class AbstractAuthenticationProcessingFilter extends GenericFilterBean
		implements ApplicationEventPublisherAware, MessageSourceAware {
	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;
			}
			// 执行session策略
			this.sessionStrategy.onAuthentication(authenticationResult, request, response);
			// 认证成功,执行后续处理
			successfulAuthentication(request, response, chain, authenticationResult);
		}
		catch (InternalAuthenticationServiceException failed) {
			unsuccessfulAuthentication(request, response, failed);
		}
		catch (AuthenticationException ex) {
			unsuccessfulAuthentication(request, response, ex);
		}
	}
	protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
			Authentication authResult) throws IOException, ServletException {
		// 1. 将当前认证信息保存到SecurityContextHolder中,一般是ThreadLocal,以便后续处理直接使用。
		SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
		context.setAuthentication(authResult);
		this.securityContextHolderStrategy.setContext(context);
		// 2. 将SecurityContext保存起来,一般是session中。这样后续的每个请求都能从中恢复当前用户信息,实现可连续交互式会话。
		this.securityContextRepository.saveContext(context, request, response);
		// 记住我功能
		this.rememberMeServices.loginSuccess(request, response, authResult);
		// 发布认证成功事件
		if (this.eventPublisher != null) {
			this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
		}
		// 认证成功后的处理。与认证成功后需要重定向跳转有关。
		this.successHandler.onAuthenticationSuccess(request, response, authResult);
	}
}

public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		// 是否为POST请求
		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 : "";
		// 构建尚未认证的token,此时没有权限
		UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
				password);
		// Allow subclasses to set the "details" property
		setDetails(request, authRequest);
		// 通过ProviderManager认证成功后,也就能获取到数据库中保存的权限了。
		return this.getAuthenticationManager().authenticate(authRequest);
	}
}

认证成功涉及的组件

组件作用描述
SessionAuthenticationStrategySession认证(成功)策略在用户认证成功后,调整session;修改sessionId或者重建session
SecurityContextHolderStrategy为处理当前请求的线程提供SecurityContext一般是保存在ThreadLocal中
SecurityContextRepository为不同请求持久化SecurityContext用户认证成功后,主要是为了完成后续请求。因此需要将SecurityContext持久化。而恢复ThreadLocal中的SecurityContext,也需要从这里获取
RememberMeServices记住我Service在认证成功后,若开启记住我功能,需要生成RemenberMeToken。后面才能使用该Token进行认证而无需用户输入密码
AuthenticationSuccessHandler认证成功后的处理器这是对于用户而言的,认证成功后需要给用户呈现什么内容/页面

由于这些都与session管理有着不可分割的关系,因此,我们留待后续聊session管理的时候再说。

小结

  • 核心认证流程
    1. 从HttpServletRequest中获取到用户名和密码
    2. 交给ProviderManager进行认证。
      DaoAuthenticationProvider会通过UserDetailsService从数据库获取用户信息,然后验证入参的密码。
    3. 认证成功后,创建SecurityContext并保存到ThreadLocal中,同时将其保存到Session中。当然还有其他扩展功能,后面再细聊。

后记

本文中,我们探讨了Spring Security的认证过滤器,并从源码层面分析了UsernamePasswordAuthenticationFilter的原理和处理流程。但是我们并没有仔细探索认证成功之后的操作。因为这些涉及到Session管理,这就与另一个过滤器SessionManagementFilter有着密不可分的关系了。所以下次,我们就聊SessionManagementFilter。届时会仔细说说。

参照

01 认证、授权、鉴权和权限控制
Authentication
JAAS 认证
【揭秘SAML协议 — Java安全认证框架的核心基石】 从初识到精通,带你领略Saml协议的奥秘,告别SSO的迷茫与困惑

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1543081.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MySQL高可用解决方案――从主从复制到InnoDB Cluster架构

2024送书福利正式起航 关注「哪吒编程」&#xff0c;提升Java技能 文末送5本《MySQL高可用解决方案――从主从复制到InnoDB Cluster架构》 大家好&#xff0c;我是哪吒。 爱奇艺每天都为数以亿计的用户提供7x24小时不间断的视频服务。通过爱奇艺的平台&#xff0c;用户可以…

由浅到深认识Java语言(23):System类

该文章Github地址&#xff1a;https://github.com/AntonyCheng/java-notes 在此介绍一下作者开源的SpringBoot项目初始化模板&#xff08;Github仓库地址&#xff1a;https://github.com/AntonyCheng/spring-boot-init-template & CSDN文章地址&#xff1a;https://blog.c…

智达方通全面预算管理系统,为企业带来更可靠的交付

对于几乎所有企业来说&#xff0c;确定提供哪些产品或服务、如何制定销售计划和配备业务以及平衡定价和预算成本以获得持续上升的利润是最基础的工作&#xff0c;对这些基础工作的评估过程可以直接决定企业未来的成功与否。然而&#xff0c;在如今这个数据激增、高速运转的新经…

【简单无脑】自动化脚本一键安装虚拟机下的MySQL服务

虚拟机安装MySQL服务 MySQL是一种广泛使用的开源关系型数据库管理系统(RDBMS)。可以在Linux操作系统下运行&#xff0c;支持多种引擎和标准的SQL语言&#xff0c;是大数据学习中和虚拟机配置中至关重要的一项服务。 但是MySQL在虚拟机中的安装步骤十分复杂繁琐&#xff0c;博…

典型内存溢出场景

说说几种典型的导致内存溢出的情况&#xff1a; 1.线程池导致内存溢出。 使用Executors.newFixedThreadPool(10);创建的线程池对象使用的工作队列是一个无上限的队列&#xff0c;队列数没有上限&#xff0c;任务数过多&#xff0c;导致队列塞满&#xff0c;内存溢出 使用了Ex…

星云小窝项目1.0——项目介绍(一)

星云小窝项目1.0——项目介绍&#xff08;一&#xff09; 文章目录 前言1. 介绍页面2. 首页2.1. 游客模式2.2. 注册用户后 3. 星云笔记3.1. 星云笔记首页3.2. 星云笔记 个人中心3.2. 星云笔记 系统管理3.3. 星云笔记 文章展示3.3. 星云笔记 新建文章 4. 数据中心5. 交流评论6. …

GPT模型部署后续:聊天机器人系统的扩展与优化

一、多轮对话支持 为了实现多轮对话支持&#xff0c;我们需要维护用户的会话上下文。这可以通过在服务器端使用一个字典来存储会话状态实现。 目录 一、多轮对话支持 下面是一个简单的扩展例子&#xff1a; 二、性能优化 三、用户界面与交互优化 下面是一个简单的HTML示例&…

springboot3使用​自定义注解+Jackson优雅实现接口数据脱敏

⛰️个人主页: 蒾酒 &#x1f525;系列专栏&#xff1a;《spring boot实战》 &#x1f30a;山高路远&#xff0c;行路漫漫&#xff0c;终有归途 目录 写在前面 内容简介 实现思路 实现步骤 1.自定义脱敏注解 2.编写脱敏策略枚举类 3.编写JSON序列化实现 4.编写测…

数据在内存里的存储(1)【整数在内存中的存储】【什么是大小端】

一.整数在内存里的存储 我们都知道&#xff0c;关于整数的二进制表示方法有三种&#xff0c;原码&#xff0c;反码和补码。而正数的原码&#xff0c;反码&#xff0c;补码都相等。而负数的表示方法各不相同。原码&#xff1a;直接将数值按照正负数的形式翻译成二进制得到的就是…

【Unity】uDD插件抓屏文字显示不清晰怎么办?

【背景】 之前介绍过用一款简称uDD&#xff08;uDesktopDuplication&#xff09;的开源插件抓取电脑桌面。整体效果不错&#xff0c;看电影很流畅。但是当切换到文档&#xff0c;或者仔细看任何UI的文字部分时&#xff0c;发现就模糊了。 【分析】 由于是依托于Canvas上的Te…

备考的秘密武器:一招清除笔迹,试卷、表格再利用!

擦除试卷笔迹的功能可以用于多种场合&#xff0c;尤其适用于教育领域和文档管理工作。以下是一些具体的应用场景&#xff1a; 教学复习&#xff1a;教师可以使用这个功能来清除已批改的试卷上的笔迹&#xff0c;以便重复使用试卷进行讲解或作为模板设计新的题目。 资料归档&a…

Linux中ifconfig无法查看ip解决

安装net-tool插件 sudo yum install net-tools

VUE中添加视频播放功能

转载https://www.cnblogs.com/gg-qq/p/10782848.html 常见错误 vue-video-player下载后‘vue-video-player/src/custom-theme.css‘找不到 解决方法 卸载原来的video-play版本 降低原来的版本 方法一 npm install vue-video-player5.0.1 --save 方法二 或者是在pack.json中直…

力扣刷题Days25-45. 跳跃游戏 II(js)

目录 1&#xff0c;题目 2&#xff0c;代码 贪心算法正向查找 3&#xff0c;学习 解题思路 具体代码处理 数组遍历的最后边界的处理&#xff1a; 1&#xff0c;题目 给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。 每个元素 nums[i] 表示从索引 i 向…

华为ensp中vrrp虚拟路由器冗余协议 原理及配置命令

CSDN 成就一亿技术人&#xff01; 作者主页&#xff1a;点击&#xff01; ENSP专栏&#xff1a;点击&#xff01; CSDN 成就一亿技术人&#xff01; ————前言————— VRRP&#xff08;Virtual Router Redundancy Protocol&#xff0c;虚拟路由器冗余协议&#xff0…

八大排序算法之希尔排序

希尔排序是插入排序的进阶版本&#xff0c;他多次调用插入排序&#xff0c;在插入排序上进行了改造&#xff0c;使其处理无序的数据时候更快 核心思想&#xff1a;1.分组 2.直接插入排序&#xff1a;越有序越快 算法思想&#xff1a; 间隔式分组&#xff0c;利用直接插入排序…

HTML 常用标签总结

本篇文章总结了一些我在学习html时所记录的标签&#xff0c;虽然总结并不是非常全面&#xff0c;但都是一些比较常用的。 html元素标签 首先一个html界面是由无数个元素标签组成的&#xff0c;每个元素具有它的属性 1.input 单行文本框 标签type属性——text <input ty…

【windows】安装 Tomcat 及配置环境变量

&#x1f468;‍&#x1f393;博主简介 &#x1f3c5;云计算领域优质创作者   &#x1f3c5;华为云开发者社区专家博主   &#x1f3c5;阿里云开发者社区专家博主 &#x1f48a;交流社区&#xff1a;运维交流社区 欢迎大家的加入&#xff01; &#x1f40b; 希望大家多多支…

视频号小店如何开店,个人可以做吗?完整版开店教程分享

大家好&#xff0c;我是电商花花。 视频号小店现在成了新的电商创业新渠道&#xff0c;这两年视频号也迎来了大爆发&#xff0c;很多朋友也都靠着视频号、视频号小店赚到了人生第一桶金&#xff0c;让很多没有接触过视频号的朋友直流口水。 那视频号小店赚钱吗&#xff1f;个人…

OpenLayers基础教程——WebGLPoints图层样式的设置方法

1、前言 前一篇博客介绍了如何在OpenLayers中使用WebGLPoints加载海量数据点的方法&#xff0c;这篇博客就来介绍一下WebGLPoints图层的样式设置问题。 2、样式运算符 在VectorLayer图层中&#xff0c;我们只需要创建一个ol.style.Style对象即可&#xff0c;WebGLPoints则不…