Spring Security(11)——匿名认证

匿名认证

目录

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

(注:原创文章,转载请注明出处。原文地址:http://elim.iteye.com/blog/2163041

原文地址:https://www.cnblogs.com/Jeely/p/11944232.html