最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring?Security權(quán)限控制的實現(xiàn)接口

 更新時間:2023年03月28日 09:18:15   作者:T.Y.Bao  
這篇文章主要介紹了Spring?Security的很多功能,在這些眾多功能中,我們知道其核心功能其實就是認(rèn)證+授權(quán)。Spring教程之Spring?Security的四種權(quá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):AuthorizationFilterAuthorizationManager

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包下的幾個配置類完成:

  • PrePostMethodSecurityConfiguration
  • SecuredMethodSecurityConfiguration

權(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}等注解中表達(dá)式使用 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)用起點(diǎn)
	 */
	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 表達(dá)式屬性
		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í)行表達(dá)式中結(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)文章

  • Nacos配置中心的配置文件的匹配規(guī)則及說明

    Nacos配置中心的配置文件的匹配規(guī)則及說明

    這篇文章主要介紹了Nacos配置中心的配置文件的匹配規(guī)則及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • idea文件上有鎖文件只讀不可編輯的解決

    idea文件上有鎖文件只讀不可編輯的解決

    這篇文章主要介紹了idea文件上有鎖文件只讀不可編輯的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • SpringBoot實用小技巧之如何動態(tài)設(shè)置日志級別

    SpringBoot實用小技巧之如何動態(tài)設(shè)置日志級別

    這篇文章主要給大家介紹了關(guān)于SpringBoot實用小技巧之如何動態(tài)設(shè)置日志級別的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用SpringBoot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • java對象轉(zhuǎn)化成String類型的四種方法小結(jié)

    java對象轉(zhuǎn)化成String類型的四種方法小結(jié)

    在java項目的實際開發(fā)和應(yīng)用中,常常需要用到將對象轉(zhuǎn)為String這一基本功能。本文就詳細(xì)的介紹幾種方法,感興趣的可以了解一下
    2021-08-08
  • Java Socket編程筆記_動力節(jié)點(diǎn)Java學(xué)院整理

    Java Socket編程筆記_動力節(jié)點(diǎn)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í)之棧和隊列

    這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)學(xué)習(xí)之棧和隊列,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有一定的幫助,需要的朋友可以參考下
    2021-05-05
  • SpringBoot下載文件的正確解法方式

    SpringBoot下載文件的正確解法方式

    這篇文章主要給大家介紹了關(guān)于SpringBoot下載文件的正確解法方式,SpringBoot是一款流行的框架,用于開發(fā)Web應(yīng)用程序,在使用SpringBoot構(gòu)建Web應(yīng)用程序時,可能需要實現(xiàn)文件下載的功能,需要的朋友可以參考下
    2023-08-08
  • SpringCloud Netfilx Ribbon負(fù)載均衡工具使用方法介紹

    SpringCloud Netfilx Ribbon負(fù)載均衡工具使用方法介紹

    Ribbon是Netflix的組件之一,負(fù)責(zé)注冊中心的負(fù)載均衡,有助于控制HTTP和TCP客戶端行為。Spring Cloud Netflix Ribbon一般配合Ribbon進(jìn)行使用,利用在Eureka中讀取的服務(wù)信息,在調(diào)用服務(wù)節(jié)點(diǎn)時合理進(jìn)行負(fù)載
    2022-12-12
  • Java中的IP地址和InetAddress類使用詳解

    Java中的IP地址和InetAddress類使用詳解

    這篇文章主要介紹了Java中的IP地址和InetAddress類使用詳解,是Java入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-10-10
  • SpringBoot如何正確配置并運(yùn)行Kafka

    SpringBoot如何正確配置并運(yùn)行Kafka

    這篇文章主要介紹了SpringBoot如何正確配置并運(yùn)行Kafka問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07

最新評論

迭部县| 谷城县| 昌江| 大化| 永年县| 贵德县| 湘潭县| 拜泉县| 秭归县| 阿克苏市| 武宣县| 乌兰县| 乳源| 保定市| 博客| 天祝| 南阳市| 宝清县| 九龙城区| 防城港市| 宣汉县| 清流县| 政和县| 西乡县| 西乌珠穆沁旗| 舟山市| 咸阳市| 萝北县| 辽阳县| 山东省| 上林县| 青海省| 邓州市| 吉安县| 郯城县| 井研县| 高雄市| 绥江县| 天峨县| 辽中县| 九龙坡区|