Spring Security权限控制的实现接口

 更新时间:2023年03月28日 09:18:15   作者:T.Y.Bao  
这篇文章主要介绍了Spring Security的很多功能,在这些众多功能中,我们知道其核心功能其实就是认证+授权。Spring教程之Spring Security的四种权限控制方式

本文样例代码地址:spring-security-oauth2.0-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);
	}
}

到此这篇关于Spring Security权限控制的实现接口的文章就介绍到这了,更多相关Spring Security权限控制内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Nacos配置中心的配置文件的匹配规则及说明

    Nacos配置中心的配置文件的匹配规则及说明

    这篇文章主要介绍了Nacos配置中心的配置文件的匹配规则及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • idea文件上有锁文件只读不可编辑的解决

    idea文件上有锁文件只读不可编辑的解决

    这篇文章主要介绍了idea文件上有锁文件只读不可编辑的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • SpringBoot实用小技巧之如何动态设置日志级别

    SpringBoot实用小技巧之如何动态设置日志级别

    这篇文章主要给大家介绍了关于SpringBoot实用小技巧之如何动态设置日志级别的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用SpringBoot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-04-04
  • java对象转化成String类型的四种方法小结

    java对象转化成String类型的四种方法小结

    在java项目的实际开发和应用中,常常需要用到将对象转为String这一基本功能。本文就详细的介绍几种方法,感兴趣的可以了解一下
    2021-08-08
  • Java Socket编程笔记_动力节点Java学院整理

    Java Socket编程笔记_动力节点Java学院整理

    Socket对于我们来说就非常实用了。下面是本次学习的笔记。主要分异常类型、交互原理、Socket、ServerSocket、多线程这几个方面阐述
    2017-05-05
  • Java数据结构学习之栈和队列

    Java数据结构学习之栈和队列

    这篇文章主要介绍了Java数据结构学习之栈和队列,文中有非常详细的代码示例,对正在学习java的小伙伴们有一定的帮助,需要的朋友可以参考下
    2021-05-05
  • SpringBoot下载文件的正确解法方式

    SpringBoot下载文件的正确解法方式

    这篇文章主要给大家介绍了关于SpringBoot下载文件的正确解法方式,SpringBoot是一款流行的框架,用于开发Web应用程序,在使用SpringBoot构建Web应用程序时,可能需要实现文件下载的功能,需要的朋友可以参考下
    2023-08-08
  • SpringCloud Netfilx Ribbon负载均衡工具使用方法介绍

    SpringCloud Netfilx Ribbon负载均衡工具使用方法介绍

    Ribbon是Netflix的组件之一,负责注册中心的负载均衡,有助于控制HTTP和TCP客户端行为。Spring Cloud Netflix Ribbon一般配合Ribbon进行使用,利用在Eureka中读取的服务信息,在调用服务节点时合理进行负载
    2022-12-12
  • Java中的IP地址和InetAddress类使用详解

    Java中的IP地址和InetAddress类使用详解

    这篇文章主要介绍了Java中的IP地址和InetAddress类使用详解,是Java入门学习中的基础知识,需要的朋友可以参考下
    2015-10-10
  • SpringBoot如何正确配置并运行Kafka

    SpringBoot如何正确配置并运行Kafka

    这篇文章主要介绍了SpringBoot如何正确配置并运行Kafka问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07

最新评论