Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

asadbekDev's avatar

SockJS pass Auth header

I am trying to open a connection in SocketJs with a passing auth header, but it's not works it gives 401 .

here is my code

  const ws = new SockJS(WebSocketBaseUrl, {
    headers: {
      "Authorization": `Bearer ${this.token}`
    }
  });

  this.stompClientSubscribeUser = Stomp.Stomp.over(ws);

  const _this = this;

  _this.stompClientSubscribeUser.connect({
    headers: {
      "Authorization": `Bearer ${_this.token}`
    }
  },
    function () {
      _this.stompClientSubscribeUser.subscribe('/user/' + _this.userId + '/queue/messages', function (sdkEvent: any) {
        _this.onMessageReceived(sdkEvent);
      });
    });
0 likes
1 reply
azimidev's avatar
const ws = new SockJS(WebSocketBaseUrl, {
  transportOptions: {
    'xhr-streaming': {
      headers: {
        "Authorization": `Bearer ${this.token}`
      }
    }
  }
});

Also, you can use ws.headers instead of passing headers in the connect() function:

const _this = this;

_this.stompClientSubscribeUser.connect({
  headers: ws.headers
},
  function () {
    _this.stompClientSubscribeUser.subscribe('/user/' + _this.userId + '/queue/messages', function (sdkEvent: any) {
      _this.onMessageReceived(sdkEvent);
    });
  });

Please or to participate in this conversation.