【问题标题】:How do I get the @AuthenticatedPrincipal from a web socket simpUser?如何从 Web 套接字 simpUser 获取 @AuthenticatedPrincipal?
【发布时间】:2021-05-23 03:38:02
【问题描述】:

我正在尝试获取在 Spring Boot 2 上通过 websocket 连接的登录用户的详细信息。为此,我目前正在使用 SimpUserRegistry 查找已连接的 SimpUser 列表。

从 Spring Boot 2.4 开始,我注意到 SimpUser 类有一个 getPrincipal() 方法,该方法返回一个通用的 Principal 对象。由于每个用户都应该通过 Spring Security 的机制登录,我认为我可以将其转换为 Spring Security 的 UserDetails 以获取登录的用户,但我意识到事实并非如此。

有谁知道我如何使用 getPrincipal 或其他方式来登录 userDetails?

【问题讨论】:

    标签: java spring spring-boot spring-websocket


    【解决方案1】:

    首先,让我们明确一点,要将getPrincipal()与websocket一起使用,您必须通过Interceptor实现websocket身份验证和授权(据我所知SpringSecurity没有自动执行此操作)。

    正确执行上述操作后,您现在可以使用getPrincipal () 方法。它将返回The identity of the principal being authenticated(可能是用户名、电子邮件...)

    您可以使用如下所示的代码:

    @MessageMapping("/test")
    public void doSomething(@Payload AppMessage appMessage, Principal principal) {
        String username = principal.getName();
        // find userDetail with username here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 2012-02-04
      • 2017-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      相关资源
      最近更新 更多