2

I want to set a username in the stomp header and set that username in the Principal object during the handshake. Created my own HandshakeHandler but i am not able to fetch that username in the method determineUser which i am overriding from DefaultHandshakeHandler.

Any help would be greatly appreciated. Here's the relevant code -->

Here's my client code -->

var from = document.getElementById('username').value;
var socket = new SockJS('/WebSocketsChat/chat');
stompClient = Stomp.over(socket);  

stompClient.connect({userName:from,sampleMsg:"Hello"},    
function(frame) {   
// Some more code here

And here's my HandShakeHandler -->

 @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
         registry.addEndpoint("/chat").setHandshakeHandler(new RandomUserNameHandshakeHandler()).withSockJS();
    }


 private class RandomUserNameHandshakeHandler extends DefaultHandshakeHandler{

     @Override
     protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String,Object> attributes){

         // Some Code that would give me the username set in Stomp Header
         // For now i am randomly generating a username and setting in principal.
         String username = "user"+"-"+ new Random().nextInt(100);
         return new UsernamePasswordAuthenticationToken(username,null);

     }
 }
user3783183
  • 23
  • 1
  • 6

1 Answers1

1

FWIW, STOMP is working on top of WebSocket. When client and server are doing WebSocket handshake, STOMP is not working yet. So obviously you won't get the username passed by stomp.connect.

I'm not sure how you authenticate a user in your app. However if you do have a authenication mechanism, you don't have to pass the username, normally there will already be an authenticated user accessible via HttpServletRequest#getUserPrincipal(), which can be accessed in HandShakeHandler. You may refer to spring docs for more details.

However if'd like to send username via connect headers, you may get it in ChannelInterceptor, as described in this answer.

Community
  • 1
  • 1
thoslin
  • 6,659
  • 6
  • 27
  • 29