I have the requirement that every user can change his own user name while he stays logged in. The problem is how to update the username (Principal
) in Spring Security`s Authentication Token?
(I have to update it, because I use the prinicpal name from the Authentication Token to identify the user in some business use cases.)
I use form based and cookie rememeber me based login so my Authentication Tokens are UsernamePaswordAuthenticationToken
and RememberMeAuthenticationToken
. Both have a field principal
where the login name is stored. Unfortunately this variable is final
, so I can not change its value.
Does anybody has an idea how Spring Security recomends to change the Principal
in the Authentication Token?
My current workarround is that I replaced the UsernamePaswordAuthenticationToken
and RememberMeAuthenticationToken
with subclasses that have an additional not final principal field and override the getPrincipal()
method to return this additional principal instead of the original one. Then I have also subclassed the two classes that generate this tokens to create my tokens instead of the original one. --- But I feel that this is a big hack.
To configure the default username, password and role, open application. properties file of your Spring Boot project and add the following three properties with the values you prefer. The above properties will change the default username, password and role.
As of Spring Security version 5.7. 1, the default username is user and the password is randomly generated and displayed in the console (e.g. 8e557245-73e2-4286-969a-ff57fe326336 ).
I've done something similar, and it's a bit of a hack but what I did was change and save the new UserDetails, and then add a new a new authentication token to the session for the updated credentials:
Authentication request = new UsernamePasswordAuthenticationToken(user.getUsername(), password);
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With