Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security: setUserPrincipal manually

In a webapplication with Spring MVC and Spring Security.

Is there a way to set UserPrincipal manually?

I need to switch to another user by an admin part of my webapplication. In my controller, is it possible to setUserPrincipal in the request? To connect as if I were someone else.

Like that: request.setUserPrincipal().getName()

like image 251
BasicCoder Avatar asked Dec 12 '11 14:12

BasicCoder


1 Answers

I've done things like this to automatically log people in after registering. It seems that it would do just what you are looking for:

Authentication authentication = new UsernamePasswordAuthenticationToken(
            userService.loadUserByUsername(u.getUserName()), null,
            AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(authentication);

I am grabbing my user from a service. This has to implement the org.springframework.security.core.userdetails.UserDetails interface.

I think this should give you a good idea of what needs doing. I remember it took me a while to piece this together from the docs.

like image 171
Robert Moskal Avatar answered Oct 26 '22 08:10

Robert Moskal