Search code examples
springspring-bootspring-securityspring-websocket

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


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!


Solution

  • 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