Spring Security:手动设置UserPrincipal

发布于 2024-12-20 22:46:01 字数 211 浏览 5 评论 0原文

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

有没有办法手动设置 UserPrincipal?

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

末蓝 2024-12-27 22:46:01

我已经做了这样的事情来让人们在注册后自动登录。看起来它会做你正在寻找的事情:

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

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

我认为这应该能让您很好地了解需要做什么。我记得我花了一段时间才从文档中拼凑出这些内容。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文