Spring Security:手动设置用户主体

9
在使用Spring MVC和Spring Security的Web应用程序中,有没有一种方法可以手动设置UserPrincipal?
我需要通过Web应用程序的管理员部分切换到另一个用户。在我的控制器中,是否可以在请求中设置setUserPrincipal?就像我是别人一样连接。
例如:request.setUserPrincipal()。getName()

您可能希望考虑使用Spring内置的SwitchUser过滤器。请参见此处的第二个回答:http://stackoverflow.com/questions/2563220/how-to-change-granted-role-temporarily-to-achieve-view-the-site-as-someone-else 或相关的JavaDocs,请查阅此处:http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.html - BobG
1个回答

8

我曾经做过类似此事的工作,实现了注册后自动登录功能。看起来这正是你所需要的:

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

我正在从一个服务中获取我的用户信息。这需要实现org.springframework.security.core.userdetails.UserDetails接口。

我认为这应该能给你一个清晰的理解,我记得我花了一段时间从文档中拼凑出来这个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接