Spring Security3源码分析(12)-AnonymousAuthenticationFilter分析

AnonymousAuthenticationFilter过滤器对应的类路径为 

org.springframework.security.web.authentication.AnonymousAuthenticationFilter 

AnonymousAuthenticationFilter过滤器是在UsernamePasswordAuthenticationFilter、BasicAuthenticationFilter、RememberMeAuthenticationFilter这些过滤器后面的,所以如果这三个过滤器都没有认证成功,则为当前的SecurityContext中添加一个经过匿名认证的token,但是通过servlet的getRemoteUser等方法是获取不到登录账号的。因为SecurityContextHolderAwareRequestFilter过滤器在AnonymousAuthenticationFilter前面。 

Java代码  

  1. //省略了日志部分  
  2. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)  
  3.         throws IOException, ServletException {  
  4.     //applyAnonymousForThisRequest永远返回ture  
  5.     if (applyAnonymousForThisRequest((HttpServletRequest) req)) {  
  6.         //如果当前SecurityContext中没有认证实体  
  7.         if (SecurityContextHolder.getContext().getAuthentication() == null) {  
  8.             //产生一个匿名认证实体,并保存到SecurityContext中  
  9.             SecurityContextHolder.getContext().setAuthentication(createAuthentication((HttpServletRequest) req));  
  10.         } else {  
  11.         }  
  12.     }  
  13.   
  14.     chain.doFilter(req, res);  
  15. }  
  16.   
  17. protected Authentication createAuthentication(HttpServletRequest request) {  
  18.     //产生匿名认证token,注意这里的key、userAttribute是通过解析标签注入的  
  19.     AnonymousAuthenticationToken auth = new AnonymousAuthenticationToken(key, userAttribute.getPassword(),  
  20.             userAttribute.getAuthorities());  
  21.     auth.setDetails(authenticationDetailsSource.buildDetails(request));  
  22.   
  23.     return auth;  
  24. }  

anonymous标签配置为。 

Xml代码  

  1. <anonymous granted-authority=“ROLE_ANONYMOUS” enabled=“true” username=“test”/>  

这里username属性容易混淆,username默认为anonymousUser,实际上是注入到UserAttribute的password变量中的。 

granted-authority属性注入到UserAttribute的authorities授权列表

    原文作者:Spring Cloud
    原文地址: https://blog.csdn.net/benjamin_whx/article/details/39204693
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞