目录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所写)