在控制器中处理websocket请求时
SecurityContextHolder.getContext().getAuthentication()
返回null。但我需要知道是哪个用户提出了请求。
到目前为止所做的尝试:
谷歌( getAuthentication() )
在websocket控制器上实现onApplicationEvent(SessionSubscribeEvent)或onApplicationEvent(SessionConnectEvent)的
我发现,在getAuthentication()的一个实现中,
RequestContextHolder.currentRequestAttributes().getSessionId()
可以注入的sessionId (8个字符)与正常请求(32个字符)的会话id不匹配:How to get Session Id in Spring WebSocketStompClient?
@Header("simpSessionId")字符串sessionId
发布于 2022-11-06 19:35:52
控制器可以监听SessionConnectEvents和SessionDisconnectEvents,其中包含8个字符的sessionId:
@EventListener
public void handleWebSocketConnectListener(SessionConnectEvent event) {
String sessionId = event.getMessage().getHeaders().get("simpSessionId", String.class);
Principal principal = event.getUser();
if (LOG.isInfoEnabled()) LOG.info("Session connect " + sessionId + ": " + principal);
sessions.put(sessionId, principal);
}
@EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
String sessionId = event.getSessionId();
if (LOG.isInfoEnabled()) LOG.info("Session disconnect " + sessionId);
sessions.remove(sessionId);
}
消息处理方法可以注入8个字符的sessionId:
@MessageMapping("/...")
public void browserToBackend(Message message, @Header("simpSessionId") String sessionId) throws Exception {
command.principal = sessions.get(sessionId);
...
https://stackoverflow.com/questions/74337376
复制相似问题