亚洲免费在线视频-亚洲啊v-久久免费精品视频-国产精品va-看片地址-成人在线视频网

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Spring Security源碼解析之權(quán)限訪問(wèn)控制是如何做到的

瀏覽:49日期:2023-07-14 17:58:54
目錄?、前文回顧一、再聊過(guò)濾器鏈二、過(guò)濾器的創(chuàng)建FilterSecurityInterceptor的創(chuàng)建ExceptionTranslationFilter的創(chuàng)建三、源碼流程FilterSecurityInterceptorExceptionTranslationFilter四、總結(jié)?、前文回顧

在實(shí)戰(zhàn)篇《話說(shuō)Spring Security權(quán)限管理(源碼詳解)》我們學(xué)習(xí)了Spring Security強(qiáng)大的訪問(wèn)控制能力,只需要進(jìn)行寥寥幾行的配置就能做到權(quán)限的控制,本篇來(lái)看看它到底是如何做到的。

一、再聊過(guò)濾器鏈

源碼篇中反復(fù)提到,請(qǐng)求進(jìn)來(lái)需要經(jīng)過(guò)的是一堆過(guò)濾器形成的過(guò)濾器鏈,走完過(guò)濾器鏈未拋出異常則可以繼續(xù)訪問(wèn)后臺(tái)接口資源,而最后一個(gè)過(guò)濾器就是來(lái)判斷請(qǐng)求是否有權(quán)限繼續(xù)訪問(wèn)后臺(tái)資源,如果沒(méi)有則會(huì)將拒絕訪問(wèn)的異常往上向異常過(guò)濾器拋,異常過(guò)濾器會(huì)對(duì)異常進(jìn)行翻譯,然后響應(yīng)給客戶端。

所以,一般情況下最后一個(gè)過(guò)濾器是做權(quán)限訪問(wèn)控制的核心過(guò)濾器FilterSecurityInterceptor ,而倒數(shù)第二個(gè)是異常翻譯過(guò)濾器ExceptionTranslationFilter ,將異常進(jìn)行翻譯然后響應(yīng)給客戶端。比如我們實(shí)戰(zhàn)項(xiàng)目過(guò)濾器鏈圖解

Spring Security源碼解析之權(quán)限訪問(wèn)控制是如何做到的

二、過(guò)濾器的創(chuàng)建FilterSecurityInterceptor的創(chuàng)建

這個(gè)過(guò)濾器的配置器是 ExpressionUrlAuthorizationConfigurer ,它的父類 AbstractInterceptUrlConfigurer 中的 configure() 方法創(chuàng)建了這個(gè)過(guò)濾器。

abstract class AbstractInterceptUrlConfigurer<C extends AbstractInterceptUrlConfigurer<C, H>, H extends HttpSecurityBuilder<H>>extends AbstractHttpConfigurer<C, H> {...@Overridepublic void configure(H http) throws Exception {FilterInvocationSecurityMetadataSource metadataSource = createMetadataSource(http);if (metadataSource == null) {return;}FilterSecurityInterceptor securityInterceptor = createFilterSecurityInterceptor(http, metadataSource, http.getSharedObject(AuthenticationManager.class));if (filterSecurityInterceptorOncePerRequest != null) {securityInterceptor.setObserveOncePerRequest(filterSecurityInterceptorOncePerRequest);}securityInterceptor = postProcess(securityInterceptor);http.addFilter(securityInterceptor);http.setSharedObject(FilterSecurityInterceptor.class, securityInterceptor);}...}

這個(gè)過(guò)濾器的配置器是在 HttpSecurity 的 authorizeRequests() 方法中apply進(jìn)來(lái)的,在我們自己配置的核心配置器中使用的就是該種基于 HttpServletRequest 限制訪問(wèn)的方式。

Spring Security源碼解析之權(quán)限訪問(wèn)控制是如何做到的

ExceptionTranslationFilter的創(chuàng)建

這個(gè)過(guò)濾器的配置器是 ExceptionHandlingConfigurer ,它自己的 configure() 方法中創(chuàng)建了這個(gè)過(guò)濾器。

public final class ExceptionHandlingConfigurer<H extends HttpSecurityBuilder<H>> extendsAbstractHttpConfigurer<ExceptionHandlingConfigurer<H>, H> {...@Overridepublic void configure(H http) throws Exception {AuthenticationEntryPoint entryPoint = getAuthenticationEntryPoint(http);ExceptionTranslationFilter exceptionTranslationFilter = new ExceptionTranslationFilter(entryPoint, getRequestCache(http));if (accessDeniedHandler != null) {exceptionTranslationFilter.setAccessDeniedHandler(accessDeniedHandler);}exceptionTranslationFilter = postProcess(exceptionTranslationFilter);http.addFilter(exceptionTranslationFilter);}...}

這個(gè)過(guò)濾器的配置器是在 HttpSecurity 的 exceptionHandling() 方法中apply進(jìn)來(lái)的,和上面不同的是,這個(gè)過(guò)濾器配置器會(huì)默認(rèn)被apply進(jìn) HttpSecurity,在 WebSecurityConfigurerAdapter 中的 init() 方法,里面調(diào)用了 getHttp() 方法,這里定義了很多默認(rèn)的過(guò)濾器配置,其中就包括當(dāng)前過(guò)濾器配置。

Spring Security源碼解析之權(quán)限訪問(wèn)控制是如何做到的

三、源碼流程FilterSecurityInterceptor 進(jìn)入:doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 進(jìn)入:invoke(FilterInvocation fi) 進(jìn)入:beforeInvocation(Object object)

這個(gè)方法里面有個(gè) attributes ,里面獲取的就是當(dāng)前request請(qǐng)求所能匹配中的權(quán)限Spel表達(dá)式,比如這里是 hasRole(’ROLE_BUYER’)Spring Security源碼解析之權(quán)限訪問(wèn)控制是如何做到的 方法源碼如下,繼續(xù)往下走

protected InterceptorStatusToken beforeInvocation(Object object) {...// 獲取當(dāng)前request請(qǐng)求所能匹配中的權(quán)限Spel表達(dá)式Collection<ConfigAttribute> attributes = this.obtainSecurityMetadataSource().getAttributes(object);...// Attempt authorizationtry {this.accessDecisionManager.decide(authenticated, object, attributes);}catch (AccessDeniedException accessDeniedException) {publishEvent(new AuthorizationFailureEvent(object, attributes, authenticated,accessDeniedException));throw accessDeniedException;}...}

進(jìn)入:decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)

這里有個(gè)投票器,投票結(jié)果為1表示可以訪問(wèn)直接返回,投票結(jié)果為-1表示拒絕訪問(wèn),向上拋拒絕訪問(wèn)異常,這里使用的投票器是 WebExpressionVoter

public void decide(Authentication authentication, Object object,Collection<ConfigAttribute> configAttributes) throws AccessDeniedException {int deny = 0;for (AccessDecisionVoter voter : getDecisionVoters()) {int result = voter.vote(authentication, object, configAttributes);if (logger.isDebugEnabled()) {logger.debug('Voter: ' + voter + ', returned: ' + result);}switch (result) {case AccessDecisionVoter.ACCESS_GRANTED:return;case AccessDecisionVoter.ACCESS_DENIED:deny++;break;default:break;}}if (deny > 0) {throw new AccessDeniedException(messages.getMessage('AbstractAccessDecisionManager.accessDenied', 'Access is denied'));}// To get this far, every AccessDecisionVoter abstainedcheckAllowIfAllAbstainDecisions();}

進(jìn)入:vote(Authentication authentication, FilterInvocation fi, Collection<ConfigAttribute> attributes)

這里面其實(shí)就是使用Spring的Spel表達(dá)式進(jìn)行投票,使用請(qǐng)求中的權(quán)限表達(dá)式組裝Expression,使用Token令牌中的權(quán)限組裝EvaluationContext,然后調(diào)用 ExpressionUtils.evaluateAsBoolean(weca.getAuthorizeExpression(), ctx),

public int vote(Authentication authentication, FilterInvocation fi,Collection<ConfigAttribute> attributes) {assert authentication != null;assert fi != null;assert attributes != null;WebExpressionConfigAttribute weca = findConfigAttribute(attributes);if (weca == null) {return ACCESS_ABSTAIN;}EvaluationContext ctx = expressionHandler.createEvaluationContext(authentication,fi);ctx = weca.postProcess(ctx, fi);return ExpressionUtils.evaluateAsBoolean(weca.getAuthorizeExpression(), ctx) ? ACCESS_GRANTED: ACCESS_DENIED;}

evaluateAsBoolean() 方法里面就是調(diào)用Expression的 getValue() 方法,獲取實(shí)際的匹配結(jié)果,如下圖Spel表達(dá)式為 hasRole(’ROLE_BUYER’)Spring Security源碼解析之權(quán)限訪問(wèn)控制是如何做到的所以它實(shí)際調(diào)用的是 SecurityExpressionRoot#hasRole 方法(關(guān)于權(quán)限表達(dá)式對(duì)應(yīng)實(shí)際調(diào)用的方法,在《手把手教你如何使用Spring Security(下):訪問(wèn)控制》文章中已貼出,下面文章也補(bǔ)充一份),里面的邏輯其實(shí)就是判斷Token令牌中是否包含有 ROLE_BUYER 的角色,有的話返回true,否則返回false,如下為 SecurityExpressionRoot#hasRole 方法源碼:

private boolean hasAnyAuthorityName(String prefix, String... roles) {Set<String> roleSet = getAuthoritySet();for (String role : roles) {String defaultedRole = getRoleWithDefaultPrefix(prefix, role);if (roleSet.contains(defaultedRole)) {return true;}}return false;} 如果投票成功,則會(huì)一直返回到 invoke() 方法,再執(zhí)行后續(xù)過(guò)濾器,未拋異常表示該請(qǐng)求已經(jīng)有訪問(wèn)權(quán)限了 假如投票失敗,在 decide() 方法中會(huì)向上拋拒絕訪問(wèn)異常,一直往上拋直到被處理,往上反向跟蹤發(fā)現(xiàn)這個(gè)過(guò)濾器一直沒(méi)有處理拒絕訪問(wèn)異常,那就繼續(xù)往上個(gè)過(guò)濾器拋,就到了我們的異常翻譯過(guò)濾器 ExceptionTranslationFilter。ExceptionTranslationFilter

該過(guò)濾器的 doFilter() 方法很簡(jiǎn)單,沒(méi)有邏輯處理,只對(duì)后續(xù)過(guò)濾器拋出的異常進(jìn)行處理,源碼如下:

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req;HttpServletResponse response = (HttpServletResponse) res;try {chain.doFilter(request, response);logger.debug('Chain processed normally');}catch (IOException ex) {throw ex;}catch (Exception ex) {// Try to extract a SpringSecurityException from the stacktraceThrowable[] causeChain = throwableAnalyzer.determineCauseChain(ex);RuntimeException ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);if (ase == null) {ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);}if (ase != null) {handleSpringSecurityException(request, response, chain, ase);}else {// Rethrow ServletExceptions and RuntimeExceptions as-isif (ex instanceof ServletException) {throw (ServletException) ex;}else if (ex instanceof RuntimeException) {throw (RuntimeException) ex;}// Wrap other Exceptions. This shouldn’t actually happen// as we’ve already covered all the possibilities for doFilterthrow new RuntimeException(ex);}}}

當(dāng)拋出拒絕訪問(wèn)異常后,繼續(xù)調(diào)用 handleSpringSecurityException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, RuntimeException exception) 方法,方法里面主要將異常信息和錯(cuò)誤碼設(shè)置到響應(yīng)頭,然后響應(yīng)到客戶端,請(qǐng)求結(jié)束。

補(bǔ)充:權(quán)限表達(dá)式

權(quán)限表達(dá)式(ExpressionUrlAuthorizationConfigurer) 說(shuō)明 Spel表達(dá)式 Spel表達(dá)式實(shí)際執(zhí)行方法(SecurityExpressionOperations) permitAll() 表示允許所有,永遠(yuǎn)返回true permitAll permitAll() denyAll() 表示拒絕所有,永遠(yuǎn)返回false denyAll denyAll() anonymous() 當(dāng)前用戶是anonymous時(shí)返回true anonymous isAnonymous() rememberMe() 當(dāng)前用戶是rememberMe用戶時(shí)返回true rememberMe isRememberMe() authenticated() 當(dāng)前用戶不是anonymous時(shí)返回true authenticated isAuthenticated() fullyAuthenticated() 當(dāng)前用戶既不是anonymous也不是rememberMe用戶時(shí)返回true fullyAuthenticated isFullyAuthenticated() hasRole(“BUYER”) 用戶擁有指定權(quán)限時(shí)返回true hasRole(‘ROLE_BUYER’) hasRole(String role) hasAnyRole(“BUYER”,“SELLER”) 用于擁有任意一個(gè)角色權(quán)限時(shí)返回true hasAnyRole (‘ROLE_BUYER’,‘ROLE_BUYER’) hasAnyRole(String… roles) hasAuthority(“BUYER”) 同hasRole hasAuthority(‘ROLE_BUYER’) hasAuthority(String role) hasAnyAuthority(“BUYER”,“SELLER”) 同hasAnyRole hasAnyAuthority (‘ROLE_BUYER’,‘ROLE_BUYER’) hasAnyAuthority(String… authorities) hasIpAddress(‘192.168.1.0/24’) 請(qǐng)求發(fā)送的Ip匹配時(shí)返回true hasIpAddress(‘192.168.1.0/24’) hasIpAddress(String ipAddress),該方法在WebSecurityExpressionRoot類中 access('@rbacService.hasPermission(request, authentication)') 可以自定義Spel表達(dá)式 @rbacService.hasPermission (request, authentication) hasPermission(request, authentication) ,該方法在自定義的RbacServiceImpl類中 四、總結(jié) 訪問(wèn)控制的核心過(guò)濾器是 FilterSecurityInterceptor ,當(dāng)然這個(gè)是可選的,我們完全也可以自定義一個(gè)過(guò)濾器去處理權(quán)限訪問(wèn)。 處理訪問(wèn)異常處理的過(guò)濾器是 ExceptionTranslationFilter ,里面邏輯很簡(jiǎn)單,給response設(shè)置異常信息錯(cuò)誤碼,再返回給客戶端。

以上就是Spring Security源碼解析之權(quán)限訪問(wèn)控制是如何做到的的詳細(xì)內(nèi)容,更多關(guān)于Spring Security權(quán)限訪問(wèn)控制的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 男人操美女逼视频 | 国产成人福利美女观看视频 | 亚洲国语在线视频手机在线 | 国产一级精品视频 | 精品国产_亚洲人成在线高清 | 国产成人亚洲合集青青草原精品 | 高清国产美女一级a毛片录 高清国产亚洲va精品 | 九九久久精品这里久久网 | 中文字幕日韩一区二区不卡 | 亚洲视频精选 | 草草影院在线播放 | 亚洲精品综合 | 久久中精品中文 | 亚洲精品久久99久久 | 成人免费看黄网址 | 在线欧美精品一区二区三区 | 日本黄页网站在线观看 | 最刺激黄a大片免费观看 | 欧美三级在线观看不卡视频 | 色婷婷激婷婷深爱五月老司机 | 欧美一级成人免费大片 | 韩国主播19福利视频在线 | 成人午夜在线视频 | 精品9e精品视频在线观看 | 久久成人a毛片免费观看网站 | 91视频天堂 | 亚洲免费成人网 | 日本成人免费在线观看 | 亚洲天堂男 | 美女张开腿让人桶 | 欧美成人福利 | 精品欧美成人bd高清在线观看 | 中日韩一级片 | 国产精品男人的天堂 | 欧美综合自拍亚洲综合 | 在线欧美国产 | 亚洲国产区 | 99久久综合精品国产 | 欧美一级乱理片免费观看 | 国产3区 | 热久久91 |