Spring Security: setUserPrincipal manually
Asked Answered
C

1

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

Cogen answered 12/12, 2011 at 14:55 Comment(1)
You may want to consider using the SwitchUser filter built into Spring. See the second answer here: #2563720 or the relevant JavaDocs here: static.springsource.org/spring-security/site/docs/3.0.x/apidocs/…Thelmathem
A
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.

Absorbance answered 13/10, 2013 at 18:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.