I currently log users in programmatically (like when they login through Facebook or other means than using my login form) with:
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(user, "", authorities)
);
What I want to do instead is log the user in as if they set the remember-me option on in the login form. So I'm guessing I need to use the RememberMeAuthenticationToken
instead of the UsernamePasswordAuthenticationToken
? But what do I put for the key
argument of the constructor?
RememberMeAuthenticationToken(String key, Object principal, Collection<? extends GrantedAuthority> authorities)
UPDATE: I'm using the Persistent Token Approach described here. So there is no key like in the Simple Hash-Based Token Approach.
This is the source for the constructor.
The key is hashed and its used to determine whether the authentication used for this user in the security context is not a 'forged' one.
Have a look at the
RememberMeAuthenicationProvider
source.So to answer your question, you need to pass the hash code of the
key
field of theAuthentication
representing the user.I assume you already have
<remember-me>
set in your configuration.The way remember-me works is it sets a cookie that is recognized when the user comes back to the site after their session has expired.
You'll have to subclass the
RememberMeServices
(TokenBased
orPersistentTokenBased
) you are using and make the onLoginSuccess() public. For example:Inject your RememberMeServices into the bean where you are doing the programmatic login. Then call
onLoginSuccess()
on it, using the UsernamePasswordAuthenticationToken that you created. That will set the cookie.UPDATE
@at improved upon this, with no subclassing of
RememberMeServices: