How to save user information in SecurityContext spring-security?

In my application, I use LDAP authentication. But I also have 2 remote services that require authentication through the method login (username, password). The method returns a security token that allows me to call other methods, i.e. I must pass the security token for the service methods as the first argument.
Therefore, I would like to get these security tokens right after a successful login using LDAP and save them in SecurityContext. I tried using the authentication-success-handler-ref of the form-login element. Using a handler, I replace the authentication object in SecurityContext with a custom AuthenticationToken, which contains not only a password, but also security tokens. But in this case, I have an exception if no authentication provider supports this token class. I know that it is also possible to store tokens in an HTTP session, but in this case I need to transfer the session to the service object, so I would like to store the tokens in the SecurityContext.

What is the best approach for handling a service security token?

+6
authentication spring-security customization
source share
2 answers

I often use the Authentication.getDetails() object to store additional information that may not be directly related to the user for feedback. This way you can store any object you want in this field (for example, HashMap), and it shares the life cycle of the Authentication object.

 HashMap<String, Object> info = new HashMap<String, Object>(); info.put("extraInfo", "info"); auth.setDetails(info); ... Map<String, Object> i = (Map<String, Object>)SecurityContextHolder.getContext().getAuthentication.getDetails(); 
+10
source share

Your implementation of "UserDetails" may contain any additional data. This is what is stored in the SecurityContext, which is later available after a successful login.

You can access it later as (It is assumed that MyUserDetails implements UserDetails)

 Object principal = SecurityContextHolder.getContext().getAuthentication(); if (principal instanceof MyUserDetails) { MyUserDetails mud = (MyUserDetails) principal; mud.getMyData(); //Extract your additional data here } 
+4
source share

All Articles