9

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

BasicCoder
  • 1,661
  • 10
  • 27
  • 42
  • You may want to consider using the SwitchUser filter built into Spring. See the second answer here: http://stackoverflow.com/questions/2563220/how-to-change-granted-role-temporarily-to-achieve-view-the-site-as-someone-els or the relevant JavaDocs here: http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.html – BobG Dec 12 '11 at 15:27

1 Answers1

8

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.

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86