Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSocket Stomp over SockJS - http custom headers

I'm using stomp.js over SockJS in my javascript client. I'm connecting to websocket using

stompClient.connect({}, function (frame) {

stomp over sockJS connection has 2 http requests:

  1. request to /info
  2. http upgrade request

the client sends all cookies. I would like to also send custom headers (e.g. XSRF header) but didn't find a way to do that. Will appreciate any help.

like image 236
user1116377 Avatar asked Aug 25 '14 13:08

user1116377


2 Answers

@Rohitdev So basically you can't send any HTTP headers using stompClient, because STOMP is layer over websockets, and only when websockets handshake happen we have possibility to send custom headers. So only SockJS can send this headers, but for some reasons don't do this: https://github.com/sockjs/sockjs-client/issues/196

like image 159
Ruslan Avatar answered Oct 19 '22 04:10

Ruslan


Custom headers:

stompClient.connect({token: "ABC123"}, function(frame) { ... code ...});

Without Custom headers:

stompClient.connect({}, function(frame) { ... code ...});

In Javascript, you can extract an STOMP header using:

  username = frame.headers['user-name'];

In the server side, if you are using Spring Framework you can implementa an Interceptor to copy the HTTP parmeters to WebSockets STOMP headers.

public class HttpSessionHandshakeInterceptor_personalised implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
            WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {


        // Set ip attribute to WebSocket session
        attributes.put("ip", request.getRemoteAddress());

        // ============================================= CODIGO PERSONAL
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        HttpServletRequest httpServletRequest = servletRequest.getServletRequest();
//        httpServletRequest.getCookies();
//        httpServletRequest.getParameter("inquiryId");
//        httpServletRequest.getRemoteUser();

         String token = httpServletRequest.getParameter("token");


      ...
    }
}

And for send messages without STOMP parameters:

function sendMessage() {
     var from = document.getElementById('from').value;
     var text = document.getElementById('text').value;
            stompClient.send("/app/chatchannel", {},
               JSON.stringify({'from':from, 'text':text}));
}

and here you are passing parameters into the STOMP headers.

function sendMessage() {
     var from = document.getElementById('from').value;
     var text = document.getElementById('text').value;
            stompClient.send("/app/chatchannel", {'token':'AA123'},
               JSON.stringify({'from':from, 'text':text}));
}
like image 9
Sergio Avatar answered Oct 19 '22 02:10

Sergio