Sunday, August 27, 2017

Spring Security

You don't need to do anything with cookies in this case.
As long as user is logged in (no matter how he logged in - using login form or "remember me"), you can access UserDetails of that user from SecurityContext, Spring Security takes care of it.
So, all you need is to put the requred information into UserDetails in UserDetailsService.loadUserByUsername() (use your own subclass of UserDetails, if necessary), and access it via SecurityContext:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
    Object principal = auth.getPrincipal();  
    if (principal instanceof UserDetails) {
        UserDetails user = (UserDetails) principal;
        ... // User is logged in, now you can access its details
    }
}
In other words, when Spring Security receives a request without active session but with remember me cookie, it uses user identity from the cookie to load UserDetails and put them into SecurityContext (and into newly created session session). Later you can access these details from SecurityContext.

No comments:

Post a Comment