论坛首页 Java企业应用论坛

(翻译)Spring Security-2.0.x参考文档“匿名认证”

浏览 1969 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-08-05  
匿名认证
17.1. 概述

有时,特别是在web请求URI安全的情况里,为每个安全对象的调用都分配一个配置属性更方便。 不同的是,有时默认需要一个ROLE_SOMETHING更好一些,这个规则只允许一些特定例外,比如登录,注销,系统的首页。 也有需要匿名认证的其他情况,比如审核拦截器查询SecurityContextHolder来确定哪个主体可以使用对应的操作。 如果它们能确定SecurityContextHolder里总是包含一个Authentication对象,而不可能是null,这些类就可以得到更多的鲁棒性。
17.2. 配置

Spring Security提供三个类来一起提供匿名认证功能。 AnonymousAuthenticationToken实现了Authentication,保存着GrantedAuthority[],用来处理匿名主体。 有一个对应的需要链入ProviderManager的AnonymousAuthenticationProvider,可以从中获得AnonymousAuthenticationTokens。 最后是AnonymousProcessingFilter,需要串链到普通认证机制后面,如果还没有存在的Authentication的话,它会自动向SecurityContextHolder添加一个AnonymousAuthenticationToken。 过滤器和认证提供器的配置如下:

<bean id="anonymousProcessingFilter"
    class="org.springframework.security.providers.anonymous.AnonymousProcessingFilter">
  <property name="key" value="foobar"/>
  <property name="userAttribute" value="anonymousUser,ROLE_ANONYMOUS"/>
</bean>

<bean id="anonymousAuthenticationProvider"
    class="org.springframework.security.providers.anonymous.AnonymousAuthenticationProvider">
  <property name="key" value="foobar"/>
</bean>
   

这个 key 会在过滤器和认证提供器之间共享,这样创建的标记可以在以后用到。 userAttribute表达式的格式是usernameInTheAuthenticationToken,grantedAuthority[,grantedAuthority]。 这和InMemoryDaoImpl中userMap属性的语法一样。

如上面所讲的,匿名认证的好处是,可以对所有的URL模式都进行安全配置。 比如:

<bean id="filterInvocationInterceptor"
    class="org.springframework.security.intercept.web.FilterSecurityInterceptor">
  <property name="authenticationManager" ref="authenticationManager"/>
  <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
  <property name="objectDefinitionSource">
    <security:filter-invocation-definition-source>
      <security:intercept-url pattern='/index.jsp' access='ROLE_ANONYMOUS,ROLE_USER'/>
      <security:intercept-url pattern='/hello.htm' access='ROLE_ANONYMOUS,ROLE_USER'/>
      <security:intercept-url pattern='/logoff.jsp' access='ROLE_ANONYMOUS,ROLE_USER'/>
      <security:intercept-url pattern='/login.jsp' access='ROLE_ANONYMOUS,ROLE_USER'/>
      <security:intercept-url pattern='/**' access='ROLE_USER'/>
    </security:filter-invocation-definition-source>
  </property>
</bean>
   

简略对匿名认证的讨论,就是AuthenticationTrustResolver接口,它对应着AuthenticationTrustResolverImpl实现。 这个接口提供了一个isAnonymous(Authentication)方法,允许感兴趣的类评估认证的特殊状态类型。 在处理AccessDeniedException异常的时候,ExceptionTranslationFilter使用这个接口。 如果抛出了一个AccessDeniedException异常,而且认证是匿名类型,那么不会抛出403(禁止)响应,这个过滤器会展开AuthenticationEntryPoint,这样主体可以正确验证。 这是一个必要的区别,否则主体会一直被认为“需要认证”,没有机会通过表单,摘要,或其他普通的认证机制登录。
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics