The opposite of: How to manually log out a user with spring security?
In my app I have register new user screen, which posts to a controller which creates a new user within db (and does a few obvious checks).I then want this new user to be automatically logged in ... I kind of want somethign like this :
SecurityContextHolder.getContext().setPrincipal(MyNewUser);
Edit Well I have almost implemented based on the answer to How to programmatically log user in with Spring Security 3.1
Authentication auth = new UsernamePasswordAuthenticationToken(MyNewUser, null);
SecurityContextHolder.getContext().setPrincipal(MyNewUser);
However, when deployed the jsp can not access my MyNewUser.getWhateverMethods()
whereas it does when normal login procedure followed. the code that works nomrally, but throws an error when logged in like above is below :
<sec:authentication property="principal.firstname" />
Once application up, open the http://localhost:8080/login URL in your browser. We will have the custom login page from spring security. Provide the valid credentials (which you used while registration), click on the “Sign In” button.
The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.
In my controller i have this, which logs user in as normal :
Authentication auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(auth);
Where user is my custom user object(implementing UserDetails) that is newly created. The getAuthorities()
method does this (just because all my users have the same role):
public Collection<GrantedAuthority> getAuthorities() { //make everyone ROLE_USER Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); GrantedAuthority grantedAuthority = new GrantedAuthority() { //anonymous inner type public String getAuthority() { return "ROLE_USER"; } }; grantedAuthorities.add(grantedAuthority); return grantedAuthorities; }
You can also inject your spring security configured UserDetailsManager
to your controller and use that to get the UserDetails
which holds the principal and authorities to avoid duplicate code:
// inject
@Autowired
private UserDetailsManager manager;
// use in your method
UserDetails userDetails = manager.loadUserByUsername (token.getUsername ());
Authentication auth = new UsernamePasswordAuthenticationToken (userDetails.getUsername (),userDetails.getPassword (),userDetails.getAuthorities ());
SecurityContextHolder.getContext().setAuthentication(auth);
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