Spring Boot WebSockets unable to find the current user (principal)

拥有回忆 提交于 2021-02-08 09:35:13

问题


After signing-in, the websockets cannot find the current user by session.getPrincipal() (it returns null).

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();
    }
}

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.

And here is the front-end (subscription)

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

But it's not working.

Please help me!


回答1:


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;
    }

Reference: Spring Boot Websocket Example



来源:https://stackoverflow.com/questions/42048024/spring-boot-websockets-unable-to-find-the-current-user-principal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!