An Authentication object was not found in the SecurityContext - Spring 3.2.2
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.
As pointed already by @Arun P Johny the root cause of the problem is that at the moment when AuthenticationSuccessEvent
is processed SecurityContextHolder
is not populated by Authentication object. So any declarative authorization checks (that must get user rights from SecurityContextHolder
) will not work. I give you another idea how to solve this problem. There are two ways how you can run your custom code immidiately after successful authentication:
- Listen to
AuthenticationSuccessEvent
- Provide your custom
AuthenticationSuccessHandler
implementation.
AuthenticationSuccessHandler
has one important advantage over first way: SecurityContextHolder
will be already populated. So just move your stateService.rowCount()
call into loginsuccesshandler.LoginSuccessHandler#onAuthenticationSuccess(...)
method and the problem will go away.
This could also happens if you put a @PreAuthorize
or @PostAuthorize
in a Bean in creation. I would recommend to move such annotations to methods of interest.