使用Spring Security在WebSocket会话上手动设置经过身份验证的用户

Ale*_*ini 5 stomp spring-security websocket spring-boot spring-websocket

我正在开发一个通过WebSocket使用STOMP消息传递的Spring Boot应用程序,该应用程序实现了RPC模式,该模式公开了公共(即,无需身份验证)和私有方法。

存在两个公共方法来注册和验证用户,因此我需要手动(以编程方式)处理用户登录,该方法通过自定义@MessageMapping操作访问。

问题是:如何验证Websocket会话的用户?

为了使用普通的MVC Web应用程序做类似的事情,我将使用类似于以下的代码:

@MessageMapping("/auth")
public Object auth() {
  List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_TEST");
  SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken(myname, "dummy", authorities));
}
Run Code Online (Sandbox Code Playgroud)

但这在websocket环境中似乎不起作用,因为当用户使用以下方法时:

@MessageMapping("/myendpoint")
public Object myEndpoint(Param params, Principal principal) {...}
Run Code Online (Sandbox Code Playgroud)

我得到错误:

org.springframework.messaging.simp.annotation.support.MissingSessionUserException: No "user" header in message
Run Code Online (Sandbox Code Playgroud)

所以问题是:如何在auth()方法中手动验证用户,以便在myEndpoint()中正确解析Principal参数?