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?
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){ ....
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());
}
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With