Spring Security 源码解读:权限控制

news2025/6/8 16:10:49

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

关于此章,官网介绍:Authorization

本文使用Spring Boot 2.7.4版本,对应Spring Security 5.7.3版本。

Introduction

认证过程中会一并获得用户权限,Authentication#getAuthorities接口方法提供权限,认证过后即是鉴权,Spring Security使用GrantedAuthority接口代表权限。早期版本在FilterChain中使用FilterSecurityInterceptor中执行鉴权过程,现使用AuthorizationFilter执行,开始执行顺序两者一致,此外,Filter中具体实现也由 AccessDecisionManager + AccessDecisionVoter 变为 AuthorizationManager

本文关注新版本的实现:AuthorizationFilterAuthorizationManager

AuthorizationManager最常用的实现类为RequestMatcherDelegatingAuthorizationManager,其中会根据你的配置生成一系列RequestMatcherEntry,每个entry中包含一个匹配器RequestMatcher和泛型类被匹配对象。

UML类图结构如下:

请添加图片描述
另外,对于 method security ,实现方式主要为AOP+Spring EL,常用权限方法注解为:

  • @EnableMethodSecurity
  • @PreAuthorize
  • @PostAuthorize
  • @PreFilter
  • @PostFilter
  • @Secured

这些注解可以用在controller方法上用于权限控制,注解中填写Spring EL表述权限信息。这些注解一起使用时的执行顺序由枚举类AuthorizationInterceptorsOrder控制:

public enum AuthorizationInterceptorsOrder {

	FIRST(Integer.MIN_VALUE),
	/**
	 * {@link PreFilterAuthorizationMethodInterceptor}
	 */
	PRE_FILTER,
	PRE_AUTHORIZE,
	SECURED,
	JSR250,
	POST_AUTHORIZE,
	/**
	 * {@link PostFilterAuthorizationMethodInterceptor}
	 */
	POST_FILTER,
	LAST(Integer.MAX_VALUE);
	...
}

而这些权限注解的提取和配置主要由org.springframework.security.config.annotation.method.configuration包下的几个配置类完成:

  • PrePostMethodSecurityConfiguration
  • SecuredMethodSecurityConfiguration

权限配置

权限配置可以通过两种方式配置:

  • SecurityFilterChain配置类配置
  • @EnableMethodSecurity 开启方法上注解配置

下面是关于SecurityFilterChain的权限配置,以及method security使用

@Configuration
// 其中prepostEnabled默认true,其他注解配置默认false,需手动改为true
@EnableMethodSecurity(securedEnabled = true)
@RequiredArgsConstructor
public class SecurityConfig {
	// 白名单
	private static final String[] AUTH_WHITELIST = ... 

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

	    // antMatcher or mvcMatcher
        http.authorizeHttpRequests()
                .antMatchers(AUTH_WHITELIST).permitAll()
                // hasRole中不需要添加 ROLE_前缀
                // ant 匹配 /admin /admin/a /admin/a/b 都会匹配上
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated();
                // denyAll慎用
//                .anyRequest().denyAll();

//        http.authorizeHttpRequests()
//                .mvcMatchers(AUTH_WHITELIST).permitAll()
//                        // 效果同上
//                        .mvcMatchers("/admin").hasRole("ADMIN")
//                        .anyRequest().denyAll();
    }

}

@PreAuthorize为例,在controller方法上使用:

@Api("user")
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

	/**
     * {@link EnableMethodSecurity} 注解必须配置在配置类上<br/>
     * {@link PreAuthorize}等注解中表达式使用 Spring EL
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin")
    public ResponseEntity<Map<String, Object>> admin() {
        return ResponseEntity.ok(Collections.singletonMap("msg","u r admin"));
    }
}

源码

配置类权限控制

AuthorizationFilter

public class AuthorizationFilter extends OncePerRequestFilter {
	
	// 在配置类中默认实现为 RequestMatcherDelegatingAuthorizationManager
	private final AuthorizationManager<HttpServletRequest> authorizationManager;

		@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// 委托给AuthorizationManager
		AuthorizationDecision decision = this.authorizationManager.check(this::getAuthentication, request);
		if (decision != null && !decision.isGranted()) {
			throw new AccessDeniedException("Access Denied");
		}
		filterChain.doFilter(request, response);
	}


}

来看看AuthorizationManager默认实现RequestMatcherDelegatingAuthorizationManager

public final class RequestMatcherDelegatingAuthorizationManager implements AuthorizationManager<HttpServletRequest> {
	// http.authorizeHttpRequests().antMatchers(AUTH_WHITELIST)...
	// SecurityFilterChain中每配置一项就会增加一个Entry
	// RequestMatcherEntry包含一个RequestMatcher和一个待鉴权对象,这里是AuthorizationManager
	private final List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings;
	...
	@Override
	public AuthorizationDecision check(Supplier<Authentication> authentication, HttpServletRequest request) {
		
		for (RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> mapping : this.mappings) {

			RequestMatcher matcher = mapping.getRequestMatcher();
			MatchResult matchResult = matcher.matcher(request);
			if (matchResult.isMatch()) {
				AuthorizationManager<RequestAuthorizationContext> manager = mapping.getEntry();
				return manager.check(authentication,
						new RequestAuthorizationContext(request, matchResult.getVariables()));
			}
		}
		return null;
	}
}

方法权限控制

总的实现基于 AOP + Spring EL

以案例中 @PreAuthorize注解的源码为例

PrePostMethodSecurityConfiguration


@Configuration(proxyBeanMethods = false)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
final class PrePostMethodSecurityConfiguration {

	private final AuthorizationManagerBeforeMethodInterceptor preAuthorizeAuthorizationMethodInterceptor;
	private final PreAuthorizeAuthorizationManager preAuthorizeAuthorizationManager = new PreAuthorizeAuthorizationManager();
	private final DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
	...

	@Autowired
	PrePostMethodSecurityConfiguration(ApplicationContext context) {
		// 设置 Spring EL 解析器
		this.preAuthorizeAuthorizationManager.setExpressionHandler(this.expressionHandler);	
		// 拦截@PreAuthorize方法
		this.preAuthorizeAuthorizationMethodInterceptor = AuthorizationManagerBeforeMethodInterceptor
				.preAuthorize(this.preAuthorizeAuthorizationManager);
		...
	}
	...
}

AuthorizationManagerBeforeMethodInterceptor

基于AOP实现

public final class AuthorizationManagerBeforeMethodInterceptor
		implements Ordered, MethodInterceptor, PointcutAdvisor, AopInfrastructureBean {

	/**
	 * 调用起点
	 */
	public static AuthorizationManagerBeforeMethodInterceptor preAuthorize() {		
		// 针对 @PreAuthorize注解提供的AuthorizationManager为PreAuthorizeAuthorizationManager
		return preAuthorize(new PreAuthorizeAuthorizationManager());
	}

	/**
	 * 初始化,创建基于@PreAuthorize注解的aop方法拦截器
	 * Creates an interceptor for the {@link PreAuthorize} annotation
	 * @param authorizationManager the {@link PreAuthorizeAuthorizationManager} to use
	 * @return the interceptor
	 */
	public static AuthorizationManagerBeforeMethodInterceptor preAuthorize(
			PreAuthorizeAuthorizationManager authorizationManager) {
		AuthorizationManagerBeforeMethodInterceptor interceptor = new AuthorizationManagerBeforeMethodInterceptor(
				AuthorizationMethodPointcuts.forAnnotations(PreAuthorize.class), authorizationManager);
		interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE.getOrder());
		return interceptor;
	}
	...	
	// 实现MethodInterceptor方法,在调用实际方法是会首先触发这个
	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
		// 先鉴权
		attemptAuthorization(mi);
		// 后执行实际方法
		return mi.proceed();
	}

	private void attemptAuthorization(MethodInvocation mi) {
		// 判断, @PreAuthorize方法用的manager就是
		// PreAuthorizeAuthorizationManager
		// 是通过上面的static类构造的
		AuthorizationDecision decision = this.authorizationManager.check(AUTHENTICATION_SUPPLIER, mi);
		if (decision != null && !decision.isGranted()) {
			throw new AccessDeniedException("Access Denied");
		}
		...
	}
	
	static final Supplier<Authentication> AUTHENTICATION_SUPPLIER = () -> {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			throw new AuthenticationCredentialsNotFoundException(
					"An Authentication object was not found in the SecurityContext");
		}
		return authentication;
	};
}

针对@PreAuthorize方法用的manager就是 PreAuthorizeAuthorizationManager#check,下面来看看

PreAuthorizeAuthorizationManager

public final class PreAuthorizeAuthorizationManager implements AuthorizationManager<MethodInvocation> {
	private final PreAuthorizeExpressionAttributeRegistry registry = new PreAuthorizeExpressionAttributeRegistry();
	private MethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();

	@Override
	public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocation mi) {
		// 获取方法上@PreAuthorize注解中的Spring EL 表达式属性
		ExpressionAttribute attribute = this.registry.getAttribute(mi);
		if (attribute == ExpressionAttribute.NULL_ATTRIBUTE) {
			return null;
		}
		// Spring EL 的 context
		EvaluationContext ctx = this.expressionHandler.createEvaluationContext(authentication.get(), mi);
		// 执行表达式中结果, 会执行SecurityExpressionRoot类中对应方法。涉及Spring EL执行原理,pass
		boolean granted = ExpressionUtils.evaluateAsBoolean(attribute.getExpression(), ctx);	
		// 返回结果
		return new ExpressionAttributeAuthorizationDecision(granted, attribute);
	}

}

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

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

相关文章

vue-router 源码解析(二)-创建路由匹配对象

文章目录基本使用导语createRouterMatcher 创建匹配路由记录addRoute 递归添加matchercreateRouteRecordMatcher 创建matchertokenizePath 解析pathtokensToParser 记录打分insertMatcher 将matcher排序总结基本使用 const routes [{path:"/",component: Demo2,nam…

爷青回!如果当年大学数据库实训选择了这款SQL工具,结局可能不一样

SQL语言逐渐成为职场人士必备的能力。很多人一直走上职场才了解什么是SQL&#xff0c;而更多人在大学就已经开始学习。 这些人一定对类似《数据库原理与应用》的课程不陌生。还记得你们是怎么熬过这门课的吗&#xff1f; 为什么说“熬”呢&#xff1f;实话说&#xff0c;数据库…

[DiceCTF 2023] rSabin

一点点学习别人的WP&#xff0c;这回看到一个大姥(r3kapig)的帖子&#xff0c;DiceCTF第二名&#xff0c;不过有好多东西一时还理解不了&#xff0c;得慢慢来。题目这个题有3个功能&#xff1a;rsa加密功能&#xff0c;p,q,N未知&#xff0c;e17低加密指数解密&#xff0c;不过…

如何通过极狐GitLab 平滑落地 Java 增量代码规范?

本文来自&#xff1a; 杨周 极狐GitLab 高级解决方案架构师 代码越写越规范是优秀开发者的成长之路&#xff0c;但很多人对老项目感到有心无力&#xff0c;因为太不规范了&#xff0c;所有人停下来一起修复也要花费很长时间&#xff0c;而且一次改动太多难以确保可靠性&#xf…

达梦8的dblink

简介&#xff1a;外部链接对象&#xff08;LINK&#xff09;是 DM 中的一种特殊的数据库实体对象&#xff0c;它记录了远程数据库的连接和路径信息&#xff0c;用于建立与远程数据的联系。通过多台数据库主库间的相互通讯&#xff0c;用户可以透明地操作远程数据库的数据&#…

我的网站上线了!

最近有段时间没有写原创文章了&#xff0c;恰好这两天正在翻阅历史文章的时候&#xff0c;发现文章中的图片竟然裂了&#xff1f;顿时冒了一身冷汗&#xff0c;因为每逢遇到这种情况&#xff0c;动辄需要花费一周的时间迁移图片。。。。。。 当我直接访问图片 url 的时候&#…

直播预告 | 数据库自治平台 KAP 监控告警架构及实例演示

线上沙龙-技术流第 25 期营业啦02月15日&#xff08;周三&#xff09;19:30KaiwuDB - B站直播间企业级数据集群往往有成百上千的各类型运算或应用同时运行&#xff0c;为保障系统的稳定可靠性&#xff0c;势必需要克服庞大数据量、复杂运算逻辑、相互关联大数据组件等重难点&am…

4年测试经验去面试10分钟就被pass,测试现在要求这么高了?

年过完了&#xff0c;大家都开始上班了&#xff0c;各位小伙伴多多注意身体&#xff0c;但是学习也别落下等 做为一名优秀的程序员&#xff0c;技术面试都是不可避免的一个环节&#xff0c;通常技术面试官都会经过本身的方式去考察程序员的技术功底与基础理论知识。 若是你参…

python基础之PyCharm介绍

课程&#xff1a;PyCharm 课程目标 PyCharm的作用下载安装PyCharmPyCharm的基本使用PyCharm的基本设置 一. PyCharm的作用 PyCharm是一种Python IDE&#xff08;集成开发环境&#xff09;&#xff0c;带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具&#x…

《Spring揭秘》记录

IOC部分 IOC不等于IOC容器&#xff0c;即使不使用spring&#xff0c;我们也可以使用IOC&#xff0c;只不过spring提供了IOC容器实现。Spring的IoC容器的功能就包含一个提供依赖注入服务的IoC Service Provider。它提供两方面的支持&#xff0c;业务对象的构建管理和业务对象间的…

GAMES202 PCSS软阴影算法细节解析

在LearnOpenGL框架的基础上实现了一遍GAMES202的PCFPCSS软阴影&#xff0c;之前学习GAMES202时一些没弄清楚的问题顺便搞清楚了。 注&#xff1a;本文中代码和shader均在笔者自学LearnOpenGL的框架中实现&#xff0c;因此有一些细节可能和GAMES202作业框架不一致&#xff0c;且…

【前端CSS面试题】2023前端最新版css模块,高频15问

&#x1f973;博 主&#xff1a;初映CY的前说(前端领域) &#x1f31e;个人信条&#xff1a;想要变成得到&#xff0c;中间还有做到&#xff01; &#x1f918;本文核心&#xff1a;博主收集的CSS面试题 目录 一、CSS必备面试题 1.CSS3新特性 2.CSS实现元素两个盒子垂…

开发技术-Java switch case 的简单用法

文章目录1. integral-selector2. case3. break4. default5. 总结最近开发写 switch 发现有的技术点还没有掌握&#xff0c;在此做个记录。ON JAVA 中文版中&#xff0c;关于 switch 的描述为&#xff1a; switch 有时也被划归为一种选择语句。根据整数表达式的值&#xff0c;s…

Vue路由 —— vue-router

在上一篇内容讲到关于单页面组件的内容&#xff0c;同时也附上补充讲了关于单页面&#xff08;SPA&#xff09;和多页面&#xff08;MPA&#xff09;之间的优缺点&#xff0c;在本篇目当中就要来讲这个路由&#xff08;vue-router&#xff09;&#xff0c;通过路由来实现页面的…

LCR测试仪测量电子元件的4种方法

当今电子元件的设计追求高性能&#xff0c; 而同时又致力于减少尺寸、 功耗和成本。 有效而准确的元件性能描述、设计、评估和制造过程中的测试&#xff0c;对于元件用户和生产厂家是至关重要的。电感、电容、电阻是电子线路中使用广泛的电子器件&#xff0c;在进行电子设计的基…

【图像处理OpenCV(C++版)】——4.5 全局直方图均衡化

前言&#xff1a; &#x1f60a;&#x1f60a;&#x1f60a;欢迎来到本博客&#x1f60a;&#x1f60a;&#x1f60a; &#x1f31f;&#x1f31f;&#x1f31f; 本专栏主要结合OpenCV和C来实现一些基本的图像处理算法并详细解释各参数含义&#xff0c;适用于平时学习、工作快…

Vue中路由缓存及activated与deactivated的详解

目录前言一&#xff0c;路由缓存1.1 引子1.2 路由缓存的方法1.2.1 keep-alive1.2.2 keep-alive标签中的include属性1.2.3 include中多组件的配置二&#xff0c;activated与deactivated2.1 引子2.2 介绍activated与deactivated2.3 解决需求三&#xff0c;整体代码总结前言 在Vu…

【C++】C++11语法 ~ lambda 表达式

&#x1f308;欢迎来到C专栏~~ lambda 表达式 (꒪ꇴ꒪(꒪ꇴ꒪ )&#x1f423;,我是Scort目前状态&#xff1a;大三非科班啃C中&#x1f30d;博客主页&#xff1a;张小姐的猫~江湖背景快上车&#x1f698;&#xff0c;握好方向盘跟我有一起打天下嘞&#xff01;送给自己的一句鸡…

WPF常用UI库和图标库(MahApps、HandyControl、LiveCharts)

WPF常用UI库和图表库&#xff08;MahApps、HandyControl、LiveCharts&#xff09; WPF有很多开源免费的UI库&#xff0c;本文主要介绍常见的MahApps、HandyControl两个UI库&#xff1b;在开发过程中经常会涉及到图表的开发&#xff0c;本文主要介绍LiveCharts开源图表库。 UI…

Dell Precision T7910 工作站做RAID

1&#xff1a;开机根据提示按Ctrl-C 2&#xff1a;进入下面界面直接按回车。Adapter是LSISAS3008IR的卡。 3&#xff1a;回车来到下面的界面&#xff0c;我们选择RAID Propertie回车。 4&#xff1a;回车来到选择RAID级别的界面。根据自己的硬盘数量和需求进行选择。 5&#xf…