You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot WebSocket请求中获取认证信息?

处理WebSocket请求时无法获取登录用户信息

在控制器中处理WebSocket请求时,

SecurityContextHolder.getContext().getAuthentication() 

返回null,但我需要知道发起请求的用户是谁。

已尝试的方案

  • 搜索得到的方案是实现ChannelInterceptor,但其所有方法中的getAuthentication()同样返回null,无法获取信息。
  • 在WebSocket控制器中实现onApplicationEvent(SessionSubscribeEvent)或onApplicationEvent(SessionConnectEvent)时,getAuthentication()仍返回null。
  • 发现在HandshakeInterceptor的实现中,getAuthentication()能返回Principal,但不知道如何将该信息在STOMP WebSocket控制器方法中使用:控制器方法无法访问线程绑定请求,使用RequestContextHolder.currentRequestAttributes().getSessionId()时会抛出No thread-bound request found异常;且通过@Header("simpSessionId") String sessionId注入的sessionId(8位)与常规请求的sessionId(32位)不匹配。

内容的提问来源于stack exchange,提问作者tbeernot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:16:07