An Authentication object was not found in the SecurityContext - Spring 3.2.2

后端 未结 6 1036
灰色年华
灰色年华 2020-12-03 04:26

I\'m trying to invoke a protected method from a class that implements the ApplicationListener interface on successful login (S

6条回答
  •  無奈伤痛
    2020-12-03 04:58

    The security's authorization check part gets the authenticated object from SecurityContext, which will be set when a request gets through the spring security filter. My assumption here is that soon after the login this is not being set. You probably can use a hack as given below to set the value.

    try {
        SecurityContext ctx = SecurityContextHolder.createEmptyContext();
        SecurityContextHolder.setContext(ctx);
        ctx.setAuthentication(event.getAuthentication());
    
        //Do what ever you want to do
    
    } finally {
        SecurityContextHolder.clearContext();
    }
    

    Update:

    Also you can have a look at the InteractiveAuthenticationSuccessEvent which will be called once the SecurityContext is set.

提交回复
热议问题