Spring Security:手动设置setUserPrincipal

Bas*_*der 9 spring spring-security userprincipal

在使用Spring MVC和Spring Security的Web应用程序中.

有没有办法手动设置UserPrincipal?

我需要通过webapplication的管理部分切换到另一个用户.在我的控制器中,是否可以在请求中设置UserPrincipal?连接好像我是别人一样.

像这样:request.setUserPrincipal().getName()

Rob*_*kal 5

我做过这样的事情,在注册后自动登录.它似乎只会满足您的需求:

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

我从服务中抓取我的用户.这必须实现org.springframework.security.core.userdetails.UserDetails接口.

我认为这应该让你很清楚需要做什么.我记得我花了一段时间从文档中将它拼凑在一起.