溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

在spring中利用security怎么實現(xiàn)自定義決策管理器

發(fā)布時間:2020-12-07 16:07:28 來源:億速云 閱讀:303 作者:Leah 欄目:編程語言

在spring中利用security怎么實現(xiàn)自定義決策管理器?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

首先介紹下Spring的決策管理器,其接口為AccessDecisionManager,抽象類為AbstractAccessDecisionManager。而我們要自定義決策管理器的話一般是繼承抽象類而不去直接實現(xiàn)接口。

在Spring中引入了投票器(AccessDecisionVoter)的概念,有無權(quán)限訪問的最終覺得權(quán)是由投票器來決定的,最常見的投票器為RoleVoter,在RoleVoter中定義了權(quán)限的前綴,先看下Spring在RoleVoter中是怎么處理授權(quán)的。

public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { 
  int result = ACCESS_ABSTAIN; 
  Collection<&#63; extends GrantedAuthority> authorities = extractAuthorities(authentication); 
  for (ConfigAttribute attribute : attributes) { 
    if (this.supports(attribute)) { 
      result = ACCESS_DENIED; 
      // Attempt to find a matching granted authority 
      for (GrantedAuthority authority : authorities) { 
        if (attribute.getAttribute().equals(authority.getAuthority())) { 
          return ACCESS_GRANTED; 
        } 
      } 
    } 
  } 
  return result; 
} 
Collection<&#63; extends GrantedAuthority> extractAuthorities(Authentication authentication) { 
  return authentication.getAuthorities(); 
} 

Authentication中是用戶及用戶權(quán)限信息,attributes是訪問資源需要的權(quán)限,然后循環(huán)判斷用戶是否有訪問資源需要的權(quán)限,如果有就返回ACCESS_GRANTED,通俗的說就是有權(quán)限。

Spring提供了3個決策管理器,至于這三個管理器是如何工作的請查看SpringSecurity源碼

AffirmativeBased 一票通過,只要有一個投票器通過就允許訪問

ConsensusBased 有一半以上投票器通過才允許訪問資源

UnanimousBased 所有投票器都通過才允許訪問

下面來實現(xiàn)一個簡單的自定義決策管理器,這個決策管理器并沒有使用投票器

public class DefaultAccessDecisionManager extends AbstractAccessDecisionManager { 
  public void decide( Authentication authentication, Object object,  
      Collection<ConfigAttribute> configAttributes)  
    throws AccessDeniedException, InsufficientAuthenticationException{ 
    SysUser user = (SysUser)authentication.getPrincipal(); 
    logger.info("訪問資源的用戶為"+user.getUsername()); 
    //如果訪問資源不需要任何權(quán)限則直接通過 
    if( configAttributes == null ) { 
      return ; 
    } 
    Iterator<ConfigAttribute> ite = configAttributes.iterator(); 
    //遍歷configAttributes看用戶是否有訪問資源的權(quán)限 
    while( ite.hasNext()){ 
      ConfigAttribute ca = ite.next(); 
      String needRole = ((SecurityConfig)ca).getAttribute(); 
      //ga 為用戶所被賦予的權(quán)限。 needRole 為訪問相應(yīng)的資源應(yīng)該具有的權(quán)限。 
      for( GrantedAuthority ga: authentication.getAuthorities()){ 
        if(needRole.trim().equals(ga.getAuthority().trim())){ 
          return; 
        } 
      } 
    } 
    throw new AccessDeniedException(""); 
  } 
} 

 decide這個方法沒有任何的返回值,需要在沒有通過授權(quán)時拋出AccessDeniedException。

如果有訪問某個資源需要同時擁有兩個或兩個以上權(quán)限的情況,這時候就要通過自定義AccessDecisionVoter來實現(xiàn)了,這個也很簡單在這里就不贅述了。如果要在頁面中使用hasRole()這樣的表達(dá)式就需要注入WebExpressionVoter了。
在SpringSecurity中自定義權(quán)限前綴

權(quán)限的前綴默認(rèn)是ROLE_,網(wǎng)上的很多例子是說,直接在配置文件中加上下面的配置就可以了。

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"> 
  <property name="rolePrefix" value="AUTH_"></property> 
</bean> 

親測不管用的,我想應(yīng)該不是我配置的問題,而是在我們配置了http auto-config="true"Spring就已經(jīng)將AccessDecisionManager初始化好了,即便配置到之前也不行,因為這個初始化是Spring自己來完成的,它并沒有把你配置的roleVoter注入到AccessDecisionManager中。那我們就來手動的注入AccessDecisionManager吧。

在http配置中有個access-decision-manager-ref屬性,可以使我們手動注入AccessDecisionManager,下面是詳細(xì)配置

<sec:http auto-config="true" access-decision-manager-ref="accessDecisionManager"> 
  <sec:access-denied-handler ref="accessDeniedHandler"/> 
  <sec:session-management invalid-session-url="/login.jsp" /> 
  <sec:intercept-url pattern="/app.jsp" access="AUTH_GG_FBGBGG"/> 
  <sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY" /> 
  <sec:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp" 
    default-target-url="/index.jsp"/> 
</sec:http> 
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased"> 
  <constructor-arg name="decisionVoters"> 
    <list> 
      <ref bean="roleVoter"/> 
      <ref bean="authenticatedVoter"/> 
    </list> 
  </constructor-arg> 
  <property name="messageSource" ref="messageSource"></property> 
</bean> 
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"> 
  <property name="rolePrefix" value=""></property> 
</bean> 
<bean id="authenticatedVoter" class="org.springframework.security.access.vote.AuthenticatedVoter" /> 

在這里我們就不用自定義的AccessDecisionManager了,直接用Spring的AffirmativeBased,因為Spring本身提供的這些決策管理器就已經(jīng)很強(qiáng)大了。

配置很簡單,要想修改權(quán)限的前綴只需要修改roleVoter中的rolePrefix就可以了,如果不要前綴就讓它為“”。

authenticatedVoter是為了支持IS_AUTHENTICATED這種認(rèn)證,authenticatedVoter提供的3種認(rèn)證,分別是

IS_AUTHENTICATED_ANONYMOUSLY 允許匿名用戶進(jìn)入

IS_AUTHENTICATED_FULLY 允許登錄用戶進(jìn)入

IS_AUTHENTICATED_REMEMBERED 允許登錄用戶和rememberMe用戶進(jìn)入

關(guān)于在spring中利用security怎么實現(xiàn)自定義決策管理器問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI