javaspringspring-securityspring-websocketspring-messaging

Spring Websockets @SendToUser without login?


I have a simple spring application with websocket functionality and everything works so far. Now I want to send a message from my server to a specific client using the @SendToUser annotation. This gives me the error "Ignoring message, no principal info available". I understand that i have no login whatsoever on my server, so every user is "anonymous" and does not have a principal (I am not using spring security for now). But every user has a session-id. Isnt it possible to use the session id somehow to differentiate between users? How can i achieve that so my users get a principal which corresponds to the session-id?


Solution

  • I think a solution might be to avoid using @SendToUser and use raw SimpMessagingTemplate and to send messages to a destination that you control for open sessions.

    For eg. assuming that you had some identity for a new websocket session, you can subscribe to a queue with that identifier in the queue name:

    stomp.subscribe("/queue/chats" + "-" + mycustomidentifier, onmessage);
    

    Now, on the Spring websocket listener side, you can direct your responses using SimpMessagingTemplate:

    @Controller
    public class MyController {
    
    
        @Autowired
        private SimpMessagingTemplate simpMessagingTemplate;
    
        @MessageMapping("/chats")
        public void handleChat(@Payload ChatMessage message) {
            this.simpMessagingTemplate.convertAndSend("/queue/chats-" + "mycustomidentifier", "[" + getTimestamp() + "]:" + message.getMessage());
        }
    ....