Spring安全性:手动设置UserPrincipal

Spring安全性:手动设置UserPrincipal,spring,spring-security,userprincipal,Spring,Spring Security,Userprincipal,在具有Spring MVC和Spring Security的Web应用程序中 有没有办法手动设置UserPrincipal 我需要通过Web应用程序的管理员部分切换到其他用户。在我的控制器中,是否可以在请求中设置UserPrincipal?就好像我是另一个人 比如:request.setUserPrincipal().getName()我做过类似的事情,让人们在注册后自动登录。它似乎可以满足您的需求: Authentication authentication = new UsernamePas

在具有Spring MVC和Spring Security的Web应用程序中

有没有办法手动设置UserPrincipal

我需要通过Web应用程序的管理员部分切换到其他用户。在我的控制器中,是否可以在请求中设置UserPrincipal?就好像我是另一个人


比如:request.setUserPrincipal().getName()

我做过类似的事情,让人们在注册后自动登录。它似乎可以满足您的需求:

Authentication authentication = new UsernamePasswordAuthenticationToken(
            userService.loadUserByUsername(u.getUserName()), null,
            AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(authentication);
我正在从服务抓取我的用户。这必须实现org.springframework.security.core.userdetails.userdetails接口


我认为这应该让你对需要做什么有一个很好的了解。我记得我花了一段时间从文档中拼凑出来。

你可能想考虑使用Spring用户过滤器内置到Spring中。请参见此处的第二个答案:或此处的相关JavaDocs: