目錄web
1.1 配置spring
1.2 AuthenticationTrustResolveride
對於匿名訪問的用戶,Spring Security支持爲其創建一個匿名的AnonymousAuthenticationToken存放在SecurityContextHolder中,這就是所謂的匿名認證。這樣在之後進行權限認證或者作其它操做時咱們就不須要再判斷SecurityContextHolder中持有的Authentication對象是否爲null了,而直接把它當作一個正常的Authentication進行使用就OK了。對象
使用NameSpace時,http元素的使用默認就會啓用對匿名認證的支持,不過咱們也能夠經過設置http元素下的anonymous元素的enabled屬性爲false停用對匿名認證的支持。如下是anonymous元素能夠配置的屬性,以及它們的默認值。接口
<security:anonymous enabled="true" key="doesNotMatter" username="anonymousUser"granted-authority="ROLE_ANONYMOUS"/>ci
key用於指定一個在AuthenticationFilter和AuthenticationProvider之間共享的值。username用於指定匿名用戶所對應的用戶名,granted-authority用於指定匿名用戶所具備的權限。it
與匿名認證相關的類有三個,AnonymousAuthenticationToken將做爲一個Authentication的實例存放在SecurityContextHolder中;過濾器運行到AnonymousAuthenticationFilter時,若是SecurityContextHolder中持有的Authentication仍是空的,則AnonymousAuthenticationFilter將建立一個AnonymousAuthenticationToken並存放在SecurityContextHolder中。最後一個相關的類是AnonymousAuthenticationProvider,其會添加到ProviderManager的AuthenticationProvider列表中,以支持對AnonymousAuthenticationToken的認證。AnonymousAuthenticationToken的認證是在AbstractSecurityInterceptor中的beforeInvocation()方法中進行的。使用http元素定義時這些bean都是會自動定義和添加的。若是須要手動定義這些bean的話,那麼能夠以下定義:io
<bean id="anonymousAuthFilter"class
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]的形式進行定義的。
AuthenticationTrustResolver是一個接口,其中定義有兩個方法,isAnonymous()和isRememberMe(),它們都接收一個Authentication對象做爲參數。它有一個默認實現類AuthenticationTrustResolverImpl,Spring Security就是使用它來判斷一個SecurityContextHolder持有的Authentication是否AnonymousAuthenticationToken或RememberMeAuthenticationToken。如當ExceptionTranslationFilter捕獲到一個AccessDecisionManager後就會使用它來判斷當前Authentication對象是否爲一個AnonymousAuthenticationToken,若是是則交由AuthenticationEntryPoint處理,不然將返回403錯誤碼。
(注:本文是基於Spring Security3.1.6所寫)