Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 518
kentobi Avatar asked Aug 01 '14 14:08

kentobi


2 Answers

Use @SendToUser and add "/user/" in front of queue when subscribing (only subscriber side). Rest works magic :-)

Instead of

Java Server: @SendTo("/topic/showResult")

and

JS Client: stompClient.subscribe('/topic/showResult', function(calResult){  ....

use:

Java Server: @SentToUser("/topic/showResult")

and

JS Client: stompClient.subscribe('/user/topic/showResult', function(calResult){ ....

like image 51
R.A Avatar answered Sep 23 '22 08:09

R.A


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());
    }
....
like image 42
Biju Kunjummen Avatar answered Sep 21 '22 08:09

Biju Kunjummen