问题描述
登录后,websockets 无法通过 session.getPrincipal()
找到当前用户(返回 null).
After signing-in, the websockets cannot find the current user by session.getPrincipal()
(it returns null).
这是 WebSockets 的 Java 代码:
Here is the Java code for WebSockets:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/queue", "/topic");
config.setApplicationDestinationPrefixes("/socket");
config.setUserDestinationPrefix("/user");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/app").withSockJS();
}
}
这似乎是一个 Spring Boot 错误 - 我正在使用 1.3.8 RELEASE
.刷新页面后,正确获取登录用户.
It seems like a Spring Boot bug - I am using 1.3.8 RELEASE
. After refreshing the page, it gets the logged-in user properly.
这里是前端(订阅)
ngstomp.subscribeTo('/user/queue/message')
.callback(function(response) {
console.log('Test');
})
.withBodyInJson()
.connect();
I tried this solution: https://www.javacodegeeks.com/2014/11/spring-boot-based-websocket-application-and-capturing-http-session-id.html
但它不起作用.
请帮帮我!
推荐答案
为什么需要 session.getPricncipal().Spring 提供 Principal 对象以自动注入您的控制器,如下所示.
Why you required to have session.getPricncipal(). Spring provides Principal object to be injected automatically in your controller as following.
@MessageMapping("/message")
public String processMessageFromClient(@Payload String message, Principal principal) throws Exception {
messagingTemplate.convertAndSendToUser(principal.getName(), "/queue/reply", name);
return name;
}
这篇关于Spring Boot WebSockets 无法找到当前用户(主体)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!