Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the login name for the current user with Spring Security 3.1?

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.

like image 394
Ralph Avatar asked Dec 23 '12 10:12

Ralph


People also ask

How do I change my Spring Security username and password?

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.

What is the default username for Spring Security?

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 ).


1 Answers

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);
like image 83
John Farrelly Avatar answered Sep 18 '22 14:09

John Farrelly