Spring?Security權(quán)限控制的實現(xiàn)接口
本文樣例代碼地址:spring-security-oauth2.0-sample。
關(guān)于此章,官網(wǎng)介紹:Authorization
本文使用Spring Boot 2.7.4版本,對應(yīng)Spring Security 5.7.3版本。
Introduction
認(rèn)證過程中會一并獲得用戶權(quán)限,Authentication#getAuthorities接口方法提供權(quán)限,認(rèn)證過后即是鑒權(quán),Spring Security使用GrantedAuthority接口代表權(quán)限。早期版本在FilterChain中使用FilterSecurityInterceptor中執(zhí)行鑒權(quán)過程,現(xiàn)使用AuthorizationFilter執(zhí)行,開始執(zhí)行順序兩者一致,此外,Filter中具體實現(xiàn)也由 AccessDecisionManager + AccessDecisionVoter 變?yōu)?AuthorizationManager
本文關(guān)注新版本的實現(xiàn):AuthorizationFilter和AuthorizationManager。
AuthorizationManager最常用的實現(xiàn)類為RequestMatcherDelegatingAuthorizationManager,其中會根據(jù)你的配置生成一系列RequestMatcherEntry,每個entry中包含一個匹配器RequestMatcher和泛型類被匹配對象。
UML類圖結(jié)構(gòu)如下:

另外,對于 method security ,實現(xiàn)方式主要為AOP+Spring EL,常用權(quán)限方法注解為:
@EnableMethodSecurity@PreAuthorize@PostAuthorize@PreFilter@PostFilter@Secured
這些注解可以用在controller方法上用于權(quán)限控制,注解中填寫Spring EL表述權(quán)限信息。這些注解一起使用時的執(zhí)行順序由枚舉類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);
...
}
而這些權(quán)限注解的提取和配置主要由org.springframework.security.config.annotation.method.configuration包下的幾個配置類完成:
PrePostMethodSecurityConfigurationSecuredMethodSecurityConfiguration
等
權(quán)限配置
權(quán)限配置可以通過兩種方式配置:
SecurityFilterChain配置類配置@EnableMethodSecurity開啟方法上注解配置
下面是關(guān)于SecurityFilterChain的權(quán)限配置,以及method security使用
@Configuration
// 其中prepostEnabled默認(rèn)true,其他注解配置默認(rèn)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"));
}
}
源碼
配置類權(quán)限控制
AuthorizationFilter
public class AuthorizationFilter extends OncePerRequestFilter {
// 在配置類中默認(rèn)實現(xiàn)為 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默認(rèn)實現(xiàn)RequestMatcherDelegatingAuthorizationManager:
public final class RequestMatcherDelegatingAuthorizationManager implements AuthorizationManager<HttpServletRequest> {
// http.authorizeHttpRequests().antMatchers(AUTH_WHITELIST)...
// SecurityFilterChain中每配置一項就會增加一個Entry
// RequestMatcherEntry包含一個RequestMatcher和一個待鑒權(quán)對象,這里是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;
}
}
方法權(quán)限控制
總的實現(xiàn)基于 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) {
// 設(shè)置 Spring EL 解析器
this.preAuthorizeAuthorizationManager.setExpressionHandler(this.expressionHandler);
// 攔截@PreAuthorize方法
this.preAuthorizeAuthorizationMethodInterceptor = AuthorizationManagerBeforeMethodInterceptor
.preAuthorize(this.preAuthorizeAuthorizationManager);
...
}
...
}
AuthorizationManagerBeforeMethodInterceptor
基于AOP實現(xiàn)
public final class AuthorizationManagerBeforeMethodInterceptor
implements Ordered, MethodInterceptor, PointcutAdvisor, AopInfrastructureBean {
/**
* 調(diào)用起點
*/
public static AuthorizationManagerBeforeMethodInterceptor preAuthorize() {
// 針對 @PreAuthorize注解提供的AuthorizationManager為PreAuthorizeAuthorizationManager
return preAuthorize(new PreAuthorizeAuthorizationManager());
}
/**
* 初始化,創(chuàng)建基于@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;
}
...
// 實現(xiàn)MethodInterceptor方法,在調(diào)用實際方法是會首先觸發(fā)這個
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
// 先鑒權(quán)
attemptAuthorization(mi);
// 后執(zhí)行實際方法
return mi.proceed();
}
private void attemptAuthorization(MethodInvocation mi) {
// 判斷, @PreAuthorize方法用的manager就是
// PreAuthorizeAuthorizationManager
// 是通過上面的static類構(gòu)造的
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);
// 執(zhí)行表達式中結(jié)果, 會執(zhí)行SecurityExpressionRoot類中對應(yīng)方法。涉及Spring EL執(zhí)行原理,pass
boolean granted = ExpressionUtils.evaluateAsBoolean(attribute.getExpression(), ctx);
// 返回結(jié)果
return new ExpressionAttributeAuthorizationDecision(granted, attribute);
}
}
到此這篇關(guān)于Spring Security權(quán)限控制的實現(xiàn)接口的文章就介紹到這了,更多相關(guān)Spring Security權(quán)限控制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot實用小技巧之如何動態(tài)設(shè)置日志級別
這篇文章主要給大家介紹了關(guān)于SpringBoot實用小技巧之如何動態(tài)設(shè)置日志級別的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用SpringBoot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
java對象轉(zhuǎn)化成String類型的四種方法小結(jié)
在java項目的實際開發(fā)和應(yīng)用中,常常需要用到將對象轉(zhuǎn)為String這一基本功能。本文就詳細的介紹幾種方法,感興趣的可以了解一下2021-08-08
Java Socket編程筆記_動力節(jié)點Java學(xué)院整理
Socket對于我們來說就非常實用了。下面是本次學(xué)習(xí)的筆記。主要分異常類型、交互原理、Socket、ServerSocket、多線程這幾個方面闡述2017-05-05
Java數(shù)據(jù)結(jié)構(gòu)學(xué)習(xí)之棧和隊列
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)學(xué)習(xí)之棧和隊列,文中有非常詳細的代碼示例,對正在學(xué)習(xí)java的小伙伴們有一定的幫助,需要的朋友可以參考下2021-05-05
SpringCloud Netfilx Ribbon負(fù)載均衡工具使用方法介紹
Ribbon是Netflix的組件之一,負(fù)責(zé)注冊中心的負(fù)載均衡,有助于控制HTTP和TCP客戶端行為。Spring Cloud Netflix Ribbon一般配合Ribbon進行使用,利用在Eureka中讀取的服務(wù)信息,在調(diào)用服務(wù)節(jié)點時合理進行負(fù)載2022-12-12

