Spring Security3源码分析-AnonymousAuthenticationFilter分析
程序员文章站
2022-03-02 11:03:18
...
AnonymousAuthenticationFilter过滤器对应的类路径为
org.springframework.security.web.authentication.AnonymousAuthenticationFilter
AnonymousAuthenticationFilter过滤器是在UsernamePasswordAuthenticationFilter、BasicAuthenticationFilter、RememberMeAuthenticationFilter这些过滤器后面的,所以如果这三个过滤器都没有认证成功,则为当前的SecurityContext中添加一个经过匿名认证的token,但是通过servlet的getRemoteUser等方法是获取不到登录账号的。因为SecurityContextHolderAwareRequestFilter过滤器在AnonymousAuthenticationFilter前面。
anonymous标签配置为。
这里username属性容易混淆,username默认为anonymousUser,实际上是注入到UserAttribute的password变量中的。
granted-authority属性注入到UserAttribute的authorities授权列表
org.springframework.security.web.authentication.AnonymousAuthenticationFilter
AnonymousAuthenticationFilter过滤器是在UsernamePasswordAuthenticationFilter、BasicAuthenticationFilter、RememberMeAuthenticationFilter这些过滤器后面的,所以如果这三个过滤器都没有认证成功,则为当前的SecurityContext中添加一个经过匿名认证的token,但是通过servlet的getRemoteUser等方法是获取不到登录账号的。因为SecurityContextHolderAwareRequestFilter过滤器在AnonymousAuthenticationFilter前面。
//省略了日志部分 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { //applyAnonymousForThisRequest永远返回ture if (applyAnonymousForThisRequest((HttpServletRequest) req)) { //如果当前SecurityContext中没有认证实体 if (SecurityContextHolder.getContext().getAuthentication() == null) { //产生一个匿名认证实体,并保存到SecurityContext中 SecurityContextHolder.getContext().setAuthentication(createAuthentication((HttpServletRequest) req)); } else { } } chain.doFilter(req, res); } protected Authentication createAuthentication(HttpServletRequest request) { //产生匿名认证token,注意这里的key、userAttribute是通过解析标签注入的 AnonymousAuthenticationToken auth = new AnonymousAuthenticationToken(key, userAttribute.getPassword(), userAttribute.getAuthorities()); auth.setDetails(authenticationDetailsSource.buildDetails(request)); return auth; }
anonymous标签配置为。
<anonymous granted-authority="ROLE_ANONYMOUS" enabled="true" username="test"/>
这里username属性容易混淆,username默认为anonymousUser,实际上是注入到UserAttribute的password变量中的。
granted-authority属性注入到UserAttribute的authorities授权列表