Spring Security AuthenticationCredentialsNotFoundException,SecurityContextHolder.getContext为null

时间:2016-07-11 14:23:25

标签: java spring spring-security

我有一个奇怪的错误,几个小时的调试,我无法理解。

更新1:我使用在Tomcat 7上运行的Spring Security 4.0.3。

问题接近this questionSecurityContextHolder期间response.redirect()可能丢失,但答案无效。

问题似乎也接近this question,但答案对我来说毫无意义。

这是我的配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class ProjectSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/login").anonymous();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser(Constants.PROFIL_ADMIN).password(Constants.PROFIL_ADMIN).
            roles("ADMIN","TEST_SERVICE");
    }
}

登录后,我尝试获取安全网址:

@RequestMapping(value = "/myurl", method = RequestMethod.GET)
@ResponseBody
public boolean getTestService(HttpServletRequest request)
        throws SQLException, PoRulesException {

    System.out.println("get security context");
    System.out.println("--------------------");
    SecurityContext secuContext = (SecurityContext) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
    System.out.println(secuContext);
    System.out.println("get security context holder");
    System.out.println(SecurityContextHolder.getContext());

    return testService.getTestMethod();
}

服务内的方法

@Secured("ROLE_TEST_SERVICE")
public boolean getTestMethod() {
    Sysout.out.println("Hiii")
    return true
}

现在,日志不起作用时:

INFO    2016-07-11 15:57:00,006 [http-bio-8080-exec-3] com.po.mvc.controller.LoginController  - Login
INFO    2016-07-11 15:57:00,057 [http-bio-8080-exec-3] com.po.mvc.controller.LoginController  - User : axel
INFO    2016-07-11 15:57:00,065 [http-bio-8080-exec-3] com.po.mvc.controller.LoginController  - Authenticate : true
INFO    2016-07-11 15:57:00,065 [http-bio-8080-exec-3] com.po.mvc.controller.LoginController  - Authenticate : org.springframework.security.authentication.UsernamePasswordAuthenticationToken@bbbc4f45: Principal: org.springframework.security.core.userdetails.User@fc8a: Username: ADM; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_CONSULTER_CA,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 613DFE47B2CE6E29DA3C227F8E028590; Granted Authorities: ROLE_ADMIN, ROLE_TEST_SERVICE
get security context
--------------------
org.springframework.security.core.context.SecurityContextImpl@bbbc4f45: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@bbbc4f45: Principal: org.springframework.security.core.userdetails.User@fc8a: Username: ADM; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_CONSULTER_CA,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 613DFE47B2CE6E29DA3C227F8E028590; Granted Authorities: ROLE_ADMIN, ROLE_TEST_SERVICE
get security context holder
org.springframework.security.core.context.SecurityContextImpl@ffffffff: Null authentication
ERROR   2016-07-11 15:57:01,960 [http-bio-8080-exec-10] com.po.exception.GlobalControllerExceptionHandler  - org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:378)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:222)
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
    at com.po.service.CAService$$EnhancerBySpringCGLIB$$f6e21857.getVarAndPrevCa(<generated>)
    at com.po.mvc.controller.CaController.getVarAndPrevCa(CaController.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:304)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

当它工作时。我只是看到没有区别...... Spring上下文已设置并包含凭证为sysout proove但SecurityContextHolder未设置。

INFO    2016-07-11 16:09:45,374 [http-bio-8080-exec-3] com.po.mvc.controller.LoginController  - Login
INFO    2016-07-11 16:09:45,393 [http-bio-8080-exec-3] com.po.mvc.controller.LoginController  - User : axel
INFO    2016-07-11 16:09:45,395 [http-bio-8080-exec-3] com.po.mvc.controller.LoginController  - Authenticate : true
INFO    2016-07-11 16:09:45,395 [http-bio-8080-exec-3] com.po.mvc.controller.LoginController  - Authenticate : org.springframework.security.authentication.UsernamePasswordAuthenticationToken@bbbc4f45: Principal: org.springframework.security.core.userdetails.User@fc8a: Username: ADM; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_TEST_SERVICE; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 613DFE47B2CE6E29DA3C227F8E028590; Granted Authorities: ROLE_ADMIN, ROLE_TEST_SERVICE
get security context
--------------------
org.springframework.security.core.context.SecurityContextImpl@bbbc4f45: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@bbbc4f45: Principal: org.springframework.security.core.userdetails.User@fc8a: Username: ADM; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_TEST_SERVICE Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 613DFE47B2CE6E29DA3C227F8E028590; Granted Authorities: ROLE_ADMIN, ROLE_CONSULTER_CA, ROLE_USER
get security context holder
org.springframework.security.core.context.SecurityContextImpl@4440cc59: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@4440cc59: Principal: org.springframework.security.core.userdetails.User@fc8a: Username: ADM; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_CONSULTER_CA,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 19994511EEE72462E8D680CDADCFEC4C; Granted Authorities: ROLE_ADMIN, ROLE_CONSULTER_CA, ROLE_USER

INFO    2016-07-11 16:09:46,879 [http-bio-8080-exec-3] Hiii

何时起作用与不起作用的唯一区别是:

  • 从我的网站页面连接时起作用,例如我mywebsite.com是公开的,并且mywebsite.com/login?user=me它正常工作
  • 但如果我来自Google mywebsite.com/login?user=me
  • ,则无效

会话属性SPRING_SECURITY_CONTEXT在两种情况下均已设置,但SecurityContextHolder未在@Secured line 222

中触发异常

我不想在方法中使用手动检查SecurityContextHolder等技巧(重定向后),如果null设置会话属性SPRING_SECURITY_CONTEXT不是{{1}我希望在根目录修复问题。

2 个答案:

答案 0 :(得分:5)

假设您无法与现有的SSO提供商集成,以下解决方案可能是您所希望的最佳解决方案。

从根本上说,除非你将自己限制在容器中的单个线程(这是一个可怕的想法),否则你所做的事情是行不通的。来自SecurityContextHolder上的文档:

  

将给定的SecurityContext与当前的执行线程相关联。

这很重要 - 当前执行线程。如果您发出了由线程A处理的登录请求,那么您尝试转到安全页面,但此请求由线程B处理,那么您在A上设置的SecurityContext不< / em>可在B上使用。

Spring Security能够通过在会话中存储安全上下文并根据需要存储/获取它来为您处理此问题(请参阅org.springframework.security.web.session.SessionManagementFilter)。但是,您需要对配置进行一些更改。

首先,您需要创建一个从AbstractAuthenticationProcessingFilter扩展的新类,并覆盖attemptAuthentication方法。然后需要注册此新过滤器,并且需要替换现有的org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter。这个课程也是一个很好的地方,可以让我们了解这一切是如何挂在一起的,以及你可以配置的内容。

这个新的过滤器可以按照

的方式行事
public Authentication attemptAuthentication(HttpServletRequest request,
    HttpServletResponse response) throws AuthenticationException {
    UserLDAP ldapUser = CorpLDAP.findUser(request);
    User user = new User(ldapUser.getProfil(), ldapUser.getPwd(), Collections.emptyList());
    return new UsernamePasswordAuthenticationToken(user, "", Collections.emptyList());
}

这将返回一个完全通过身份验证的用户,以后可以使用。这将存储在SecurityContextHolder中,并且可以轻松检索。它也将存储在会话中(如果已配置),因此我建议确保它是可序列化的。由于您没有使用密码,我强烈建议不要将其存储在User中。

希望这会让你朝着正确的方向前进。

答案 1 :(得分:4)

最后我在这里找到了解决方案

https://spring.io/blog/2013/07/03/spring-security-java-config-preview-web-security/

我的配置错过了这一点

  

最后一步是我们需要映射springSecurityFilterChain。我们可以   通过扩展AbstractSecurityWebApplicationInitializer轻松完成此操作   并可选择重写方法来自定义映射。

     

下面最基本的示例接受默认映射并添加   springSecurityFilterChain具有以下特征:

     

springSecurityFilterChain映射到“/ *”springSecurityFilterChain   使用ERROR和REQUEST的调度类型   springSecurityFilterChain映射在任何servlet之前插入   过滤已配置的映射

public class SecurityWebApplicationInitializer 
   extends AbstractSecurityWebApplicationInitializer {
}

只需添加该类就可以解决问题,如果没有,可以添加@Order

“WebApplicationInitializer的订购”

  

如果之后添加了任何servlet过滤器映射   调用AbstractSecurityWebApplicationInitializer,它们可能是   在springSecurityFilterChain之前意外添加。除非   应用程序包含不需要保护的过滤器实例,   springSecurityFilterChain应该在任何其他Filter映射之前。   @Order注释可用于帮助确保任何   WebApplicationInitializer以确定的顺序加载。

@Order(1)
public class SpringWebMvcInitializer extends
   AbstractAnnotationConfigDispatcherServletInitializer {

  @Override
  protected Class<?>[] getRootConfigClasses() {
    return new Class[] { HelloWebSecurityConfiguration.class };
  }
  ...
}

    @Order(2)
    public class SecurityWebApplicationInitializer 
       extends AbstractSecurityWebApplicationInitializer {
    }