目錄
1.1 配置
1.2 AuthenticationTrustResolver
對於匿名訪問的用戶,Spring Security支持為其建立一個匿名的AnonymousAuthenticationToken存放在SecurityContextHolder中,這就是所謂的匿名認證。這樣在以后進行權限認證或者做其它操作時我們就不需要再判斷SecurityContextHolder中持有的Authentication對象是否為null了,而直接把它當做一個正常的Authentication進行使用就OK了。
1.1 配置
使用NameSpace時,http元素的使用默認就會啟用對匿名認證的支持,不過我們也可以通過設置http元素下的anonymous元素的enabled屬性為false停用對匿名認證的支持。以下是anonymous元素可以配置的屬性,以及它們的默認值。
<security:anonymous enabled="true" key="doesNotMatter" username="anonymousUser"granted-authority="ROLE_ANONYMOUS"/>
key用於指定一個在AuthenticationFilter和AuthenticationProvider之間共享的值。username用於指定匿名用戶所對應的用戶名,granted-authority用於指定匿名用戶所具有的權限。
與匿名認證相關的類有三個,AnonymousAuthenticationToken將作為一個Authentication的實例存放在SecurityContextHolder中;過濾器運行到AnonymousAuthenticationFilter時,如果SecurityContextHolder中持有的Authentication還是空的,則AnonymousAuthenticationFilter將創建一個AnonymousAuthenticationToken並存放在SecurityContextHolder中。最后一個相關的類是AnonymousAuthenticationProvider,其會添加到ProviderManager的AuthenticationProvider列表中,以支持對AnonymousAuthenticationToken的認證。AnonymousAuthenticationToken的認證是在AbstractSecurityInterceptor中的beforeInvocation()方法中進行的。使用http元素定義時這些bean都是會自動定義和添加的。如果需要手動定義這些bean的話,那么可以如下定義:
<bean id="anonymousAuthFilter"
class="org.springframework.security.web.authentication.AnonymousAuthenticationFilter">
<property name="key" value="doesNotMatter" />
<property name="userAttribute" value="anonymousUser,ROLE_ANONYMOUS" />
</bean>
<bean id="anonymousAuthenticationProvider"
class="org.springframework.security.authentication.AnonymousAuthenticationProvider">
<property name="key" value="doesNotMatter" />
</bean>
key是在AnonymousAuthenticationProvider和AnonymousAuthenticationFilter之間共享的,它們必須保持一致,AnonymousAuthenticationProvider將使用本身擁有的key與傳入的AnonymousAuthenticationToken的key作比較,相同則認為可以進行認證,否則將拋出異常BadCredentialsException。userAttribute屬性是以usernameInTheAuthenticationToken,grantedAuthority[,grantedAuthority]的形式進行定義的。
1.2 AuthenticationTrustResolver
AuthenticationTrustResolver是一個接口,其中定義有兩個方法,isAnonymous()和isRememberMe(),它們都接收一個Authentication對象作為參數。它有一個默認實現類AuthenticationTrustResolverImpl,Spring Security就是使用它來判斷一個SecurityContextHolder持有的Authentication是否AnonymousAuthenticationToken或RememberMeAuthenticationToken。如當ExceptionTranslationFilter捕獲到一個AccessDecisionManager后就會使用它來判斷當前Authentication對象是否為一個AnonymousAuthenticationToken,如果是則交由AuthenticationEntryPoint處理,否則將返回403錯誤碼。
(注:本文是基於Spring Security3.1.6所寫)
