为啥“anonymousUser”Spring Security的认证
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为啥“anonymousUser”Spring Security的认证相关的知识,希望对你有一定的参考价值。
参考技术A Spring Security3的使用中,有4种方法: 一种是全部利用配置文件,将用户、权限、资源(url)硬编码在xml文件中,已经实现过,并经过验证; 二种是用户和权限用数据库存储,而资源(url)和权限的对应采用硬编码配置,目前这种方式已经实现,并经过验证。 三种是细分角色和权限,并将用户、角色、权限和资源均采用数据库存储,并且自定义过滤器,代替原有的FilterSecurityInterceptor过滤器, 并分别实现AccessDecisionManager、InvocationSecurityMetadataSourceService和UserDetailsService,并在配置文件中进行相应配置。 目前这种方式已经实现,并经过验证。 四是修改spring security的源代码,主要是修改InvocationSecurityMetadataSourceService和UserDetailsService两个类。 前者是将配置文件或数据库中存储的资源(url)提取出来加工成为url和权限列表的Map供Security使用,后者提取用户名和权限组成一个完整的(UserDetails)User对象,该对象可以提供用户的详细信息供AuthentationManager进行认证与授权使用。本回答被提问者采纳Spring Security 3.1.4:由于anonymousUser身份验证无法访问目标页面
【中文标题】Spring Security 3.1.4:由于anonymousUser身份验证无法访问目标页面【英文标题】:Spring Security 3.1.4: Cannot access target page due to anonymousUser authentication 【发布时间】:2014-11-01 23:21:58 【问题描述】:当用户密码被重置时,用户应该转到安全问题页面,而不是用户被踢回登录页面。启用 spring 调试日志后,我注意到 spring 正在创建匿名用户身份验证。
我正在使用 Spring security 3.1.4
以下是我的应用日志
2014-09-08 13:34:42,355 DEBUG | org.springframework.security.web.savedrequest.HttpSessionRequestCache | | bzyJYL3H4y4h | DefaultSavedRequest added to Session: DefaultSavedRequest[https://qa-cp/PP/enduser/securityQuestions.do?clear=true]
2014-09-08 13:34:42,355 DEBUG | org.springframework.security.web.access.ExceptionTranslationFilter | | bzyJYL3H4y4h | Calling Authentication entry point.
2014-09-08 13:34:42,355 DEBUG | org.springframework.security.web.DefaultRedirectStrategy | | bzyJYL3H4y4h | Redirecting to 'https://qa-cp/PP/index.do'
2014-09-08 13:34:42,355 DEBUG | org.springframework.security.web.context.HttpSessionSecurityContextRepository | | bzyJYL3H4y4h | SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2014-09-08 13:34:42,356 DEBUG | org.springframework.security.web.context.SecurityContextPersistenceFilter | | bzyJYL3H4y4h | SecurityContextHolder now cleared, as request processing completed
2014-09-08 13:34:43,369 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /index.do at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-08 13:34:43,370 DEBUG | org.springframework.security.web.context.HttpSessionSecurityContextRepository | | orAnz9si9ErQ | HttpSession returned null object for SPRING_SECURITY_CONTEXT
2014-09-08 13:34:43,371 DEBUG | org.springframework.security.web.context.HttpSessionSecurityContextRepository | | orAnz9si9ErQ | No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@6814b7b1. A new one will be created.
2014-09-08 13:34:43,371 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /index.do at position 2 of 12 in additional filter chain; firing Filter: 'WelcomePageRedirectFilter'
2014-09-08 13:34:43,373 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /index.do at position 3 of 12 in additional filter chain; firing Filter: 'InternalAuthenticationFilter'
2014-09-08 13:34:43,374 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /index.do at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2014-09-08 13:34:43,375 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /index.do at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2014-09-08 13:34:43,375 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /index.do at position 6 of 12 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2014-09-08 13:34:43,376 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /index.do at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2014-09-08 13:34:43,377 DEBUG | org.springframework.security.web.savedrequest.DefaultSavedRequest | | orAnz9si9ErQ | pathInfo: both null (property equals)
2014-09-08 13:34:43,378 DEBUG | org.springframework.security.web.savedrequest.DefaultSavedRequest | | orAnz9si9ErQ | queryString: arg1=clear=true; arg2=null (property not equals)
2014-09-08 13:34:43,379 DEBUG | org.springframework.security.web.savedrequest.HttpSessionRequestCache | | orAnz9si9ErQ | saved request doesn't match
2014-09-08 13:34:43,379 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /index.do at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2014-09-08 13:34:43,380 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /index.do at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2014-09-08 13:34:43,381 DEBUG | org.springframework.security.web.authentication.AnonymousAuthenticationFilter | anonymousUser | orAnz9si9ErQ | Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@905571d8: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 10.9.120.74; SessionId: C69492D05E3009DEC64122CC220B9A4B; Granted Authorities: ROLE_ANONYMOUS'
2014-09-08 13:34:43,382 DEBUG | org.springframework.security.web.FilterChainProxy | anonymousUser | orAnz9si9ErQ | /index.do at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2014-09-08 13:34:43,383 DEBUG | org.springframework.security.web.FilterChainProxy | anonymousUser | orAnz9si9ErQ | /index.do at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2014-09-08 13:34:43,384 DEBUG | org.springframework.security.web.FilterChainProxy | anonymousUser | orAnz9si9ErQ | /index.do at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
在尝试登录几分钟后,spring 对用户进行身份验证。以下是日志
2014-09-08 13:34:51,089 DEBUG | org.springframework.security.web.FilterChainProxy | | IfMNPOKYArlz | /j_spring_security_check at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-08 13:34:51,090 DEBUG | org.springframework.security.web.context.HttpSessionSecurityContextRepository | | IfMNPOKYArlz | HttpSession returned null object for SPRING_SECURITY_CONTEXT
2014-09-08 13:34:51,092 DEBUG | org.springframework.security.web.context.HttpSessionSecurityContextRepository | | IfMNPOKYArlz | No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@6814b7b1. A new one will be created.
2014-09-08 13:34:51,093 DEBUG | org.springframework.security.web.FilterChainProxy | | IfMNPOKYArlz | /j_spring_security_check at position 2 of 12 in additional filter chain; firing Filter: 'WelcomePageRedirectFilter'
2014-09-08 13:34:51,100 DEBUG | org.springframework.security.web.FilterChainProxy | | IfMNPOKYArlz | /j_spring_security_check at position 3 of 12 in additional filter chain; firing Filter: 'InternalAuthenticationFilter'
2014-09-08 13:34:51,100 DEBUG | org.springframework.security.web.FilterChainProxy | | IfMNPOKYArlz | /j_spring_security_check at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2014-09-08 13:34:51,101 DEBUG | org.springframework.security.web.FilterChainProxy | | IfMNPOKYArlz | /j_spring_security_check at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2014-09-08 13:34:51,102 DEBUG | org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter | | IfMNPOKYArlz | Request is to process authentication
2014-09-08 13:34:51,103 DEBUG | org.springframework.security.authentication.ProviderManager | | IfMNPOKYArlz | Authentication attempt using com.dc.apps.collaborationportal.security.service.CPDaoAuthenticationProvider
2014-09-08 13:34:51,110 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /j_spring_security_check at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-08 13:34:51,110 DEBUG | org.springframework.security.web.context.HttpSessionSecurityContextRepository | | orAnz9si9ErQ | HttpSession returned null object for SPRING_SECURITY_CONTEXT
2014-09-08 13:34:51,111 DEBUG | org.springframework.security.web.context.HttpSessionSecurityContextRepository | | orAnz9si9ErQ | No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@6814b7b1. A new one will be created.
2014-09-08 13:34:51,111 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /j_spring_security_check at position 2 of 12 in additional filter chain; firing Filter: 'WelcomePageRedirectFilter'
2014-09-08 13:34:51,112 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /j_spring_security_check at position 3 of 12 in additional filter chain; firing Filter: 'InternalAuthenticationFilter'
2014-09-08 13:34:51,112 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /j_spring_security_check at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2014-09-08 13:34:51,113 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /j_spring_security_check at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2014-09-08 13:34:51,114 DEBUG | org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter | | orAnz9si9ErQ | Request is to process authentication
2014-09-08 13:34:51,114 DEBUG | org.springframework.security.authentication.ProviderManager | | orAnz9si9ErQ | Authentication attempt using com.dc.apps.collaborationportal.security.service.CPDaoAuthenticationProvider
2014-09-08 13:34:51,164 DEBUG | org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter | | IfMNPOKYArlz | Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@79680fbd: Principal: org.springframework.security.core.userdetails.User@49520377: Username: test1@dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 11.22.22.33; SessionId: C69492D05E3009DEC64122CC220B9A4B; Not granted any authorities
2014-09-08 13:34:51,178 DEBUG | org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter | | orAnz9si9ErQ | Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@79680fbd: Principal: org.springframework.security.core.userdetails.User@49520377: Username: test1@dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 11.22.22.33; SessionId: C69492D05E3009DEC64122CC220B9A4B; Not granted any authorities
2014-09-08 13:34:51,355 DEBUG | org.springframework.security.web.DefaultRedirectStrategy | test1@dc.com | orAnz9si9ErQ | Redirecting to '/PP/enduser/securityQuestions.do?clear=true'
2014-09-08 13:34:51,356 DEBUG | org.springframework.security.web.context.HttpSessionSecurityContextRepository | test1@dc.com | orAnz9si9ErQ | SecurityContext stored to HttpSession: 'org.springframework.security.core.context.SecurityContextImpl@79680fbd: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@79680fbd: Principal: org.springframework.security.core.userdetails.User@49520377: Username: test1@dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 11.22.22.33; SessionId: C69492D05E3009DEC64122CC220B9A4B; Not granted any authorities'
2014-09-08 13:34:51,357 DEBUG | org.springframework.security.web.context.SecurityContextPersistenceFilter | | orAnz9si9ErQ | SecurityContextHolder now cleared, as request processing completed
2014-09-08 13:34:51,396 DEBUG | org.springframework.security.web.DefaultRedirectStrategy | test1@dc.com | IfMNPOKYArlz | Redirecting to '/PP/enduser/securityQuestions.do?clear=true'
2014-09-08 13:34:51,397 DEBUG | org.springframework.security.web.context.HttpSessionSecurityContextRepository | test1@dc.com | IfMNPOKYArlz | HttpSession is now null, but was not null at start of request; session was invalidated, so do not create a new session
2014-09-08 13:34:51,398 DEBUG | org.springframework.security.web.context.SecurityContextPersistenceFilter | | IfMNPOKYArlz | SecurityContextHolder now cleared, as request processing completed
2014-09-08 13:34:52,372 DEBUG | org.springframework.security.web.FilterChainProxy | | orAnz9si9ErQ | /enduser/securityQuestions.do?clear=true at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-08 13:34:52,373 DEBUG | org.springframework.security.web.context.HttpSessionSecurityContextRepository | | orAnz9si9ErQ | Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@79680fbd: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@79680fbd: Principal: org.springframework.security.core.userdetails.User@49520377: Username: test1@dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 11.22.22.33; SessionId: C69492D05E3009DEC64122CC220B9A4B; Not granted any authorities'
更新:security-applicationContext.xml
<beans:bean id="trustedAuthenticationFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
<beans:property name="principalRequestHeader" value="X-Remote-Authenticate"/>
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="exceptionIfHeaderMissing" value="false" />
</beans:bean>
<!-- LOCAL LOGIN CONFIGURATION -->
<http use-expressions="true" auto-config="false" disable-url-rewriting="true" entry-point-ref="loginUrlAuthenticationEntryPoint"
request-matcher-ref="localAuthRequestMatcher">
<intercept-url pattern="/admin/**" access="hasRole('ADMIN_PERMISSION')" />
<intercept-url pattern="/system/**" access="hasRole('ADMIN_PERMISSION')" />
<intercept-url pattern="/enduser/**" access="isAuthenticated()" />
<intercept-url pattern="/changePassword.do" access="permitAll"/>
<intercept-url pattern="/index.do" access="isAnonymous()" />
<custom-filter after="SECURITY_CONTEXT_FILTER" ref="welcomePageRedirectFilter" />
<custom-filter before="LOGOUT_FILTER" ref="internalAuthenticationFilter" />
<custom-filter before="FORM_LOGIN_FILTER" ref="customUsernamePasswordAuthenticationFilter"/>
<form-login login-page="/index.do" authentication-failure-handler-ref="DCAuthenticationFailureHandler" authentication-success-handler-ref="DCAuthenticationSuccessHandler" />
<http-basic />
<anonymous />
<session-management session-authentication-strategy-ref="customSessionFixationProtectionStrategy" />
<logout success-handler-ref="localLogoutSuccessHandler" />
</http>
<beans:bean id="exceptionTranslator"
class="org.springframework.security.web.access.ExceptionTranslationFilter">
<beans:constructor-arg><beans:ref bean="loginUrlAuthenticationEntryPoint" /></beans:constructor-arg>
</beans:bean>
<beans:bean id="localLogoutSuccessHandler"
class="com.dc.core.security.authentication.impl.CustomLogoutSuccessHandler">
<beans:property name="defaultTargetUrl" value="/index.do" />
</beans:bean>
将用户重定向到安全问题页面的代码
@Component
@Primary
public class CPAuthenticationSuccessHandler extends DCAuthenticationSuccessHandler
@Autowired
private CollaborationSecurityService collabSecurityService;
@Autowired
private AuthenticationFilterConfiguration authenticationConfiguration;
@Autowired
private FailedLoginsLock failedLoginsLock;
private static final String SECURITY_QUESTIONS_URL = "/enduser/securityQuestions.do?clear=true";
private static final Logger LOGGER = Logger.getInstance("dc.auth");
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException
new DefaultRedirectStrategy().sendRedirect(request, response,
this.onCPAuthenticationSuccessUrl(request, response, authentication));
public String onCPAuthenticationSuccessUrl(final HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException
LOGGER.log(Level.INFO, "Successful Authentication Principal--> " + authentication.getPrincipal());
boolean isNewSession = false;
Session session = null;
try
if (!sessionHandler.sessionAlreadyBound(sessionFactory))
session = sessionHandler.initiateSession(sessionFactory);
sessionHandler.beginTransaction(session);
isNewSession = true;
if (!SecurityHelper.isCurrentUserAnonymous()
&& collabSecurityService.needSecurityQuestionSetup(authentication.getName()))
return SECURITY_QUESTIONS_URL;
else
return super.onAuthenticationSuccessUrl(request, response, authentication);
finally
if (isNewSession)
sessionHandler.endTransaction(false, sessionFactory);
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
super.setApplicationContext(applicationContext);
我真的不知道 spring 身份验证出了什么问题。我真的很感谢有人在这方面的帮助
【问题讨论】:
能分享一下spring的配置和代码吗?看你的代码并猜测问题的本质是不可能的 @SezinKarli 我正在尝试使用代码和配置更新我的问题,但似乎我的问题已经有 30000 个字符,并且不允许我添加任何其他字符 @RanPaul 你可以删除一些日志。配置会告诉我们更多... @Evgeni 使用 securityContext.xml 更新了问题 【参考方案1】:我在 spring security 5 中遇到了同样的问题,也许可以帮助其他有类似问题的人。
固定过滤器调用的优先级可以帮助解决这个问题。
如果您的身份验证过滤器在调用 SecurityContextPersistenceFilter
类之前对您的用户进行身份验证,则此类会重置上下文并且您的用户会从上下文中清除:
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext contextBeforeChainExecution = this.repo.loadContext(holder);
try
SecurityContextHolder.setContext(contextBeforeChainExecution);
...
在下一个过滤器链中,您的已验证用户丢失,AnonymousAuthenticationFilter
在身份验证为空时注册 anonymousUser
。
最终你必须在SecurityContextPersistenceFilter
之后更改过滤器的优先级。
例如,在非 xml 配置中,您可以像这样设置过滤器优先级:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception
...
http.addFilterAfter(YOUR_FILTER_CLASS, SecurityContextPersistenceFilter.class);
...
【讨论】:
以上是关于为啥“anonymousUser”Spring Security的认证的主要内容,如果未能解决你的问题,请参考以下文章
Spring安全类工作在不同的端口尝试使用来自apk的有效凭据登录,得到“**anonymousUser**”
如何修复“AnonymousUser”对象没有属性“配置文件”错误?
django - AttributeError:'AnonymousUser'对象没有属性'todo'
Django登录AttributeError:'AnonymousUser'对象没有属性'_meta'