2011-12-12 38 views
6

在Spring MVC和Spring Security的Web应用程序中。Spring Security:手动设置setUserPrincipal

有没有办法手动设置UserPrincipal?

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

就像是:request.setUserPrincipal()的getName()

+0

您可能需要考虑使用Spring内置的SwitchUser过滤器。看到第二个答案在这里:http://stackoverflow.com/questions/2563220/how-to-change-granted-role-temporarily-to-achieve-view-the-site-as-someone-els或相关的JavaDocs在这里:http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.html – BobG

回答

4

我已经注册完成后,像这样的事情自动登录的人。它似乎只是你正在寻找的东西:

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

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

我认为这应该给你一个关于需要做什么的好主意。我记得我花了一段时间才从文档中拼凑出来。