Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Websocket connection with authorization header

I am working on a real time websocket application where in the server is coded with .Net core where as clients can be in several different languages. The way I decided to secure the server is JWT, i.e. to accept a socket connection only from a request with valid JWT. I could successfully do so with .Net client, here is my code:

        _client = new WebSocket("ws://localhost:8080/api/SocketDock","",null,new List<KeyValuePair<string, string>>()
        { new KeyValuePair<string, string>(
            "Authorization", "Bearer eyJhbGciOiJIUzI1.....") 
        });

This is working perfectly fine with .net core client websocket. However, I am not able to do the same with Angular client. I went through several articles somehow ending up with an answer that it is not possible. However, it is seems to me a matter of common sense that if a protocol or handshake is possible in one language, it must be possible in others too.

Can someone guide me proper way to achieve the same with any Angular client.

like image 493
Murtuza Kabul Avatar asked May 06 '26 10:05

Murtuza Kabul


1 Answers

The answer is that the javascript native websocket api doesn't support addition of custom headers because its simply not necessary.

https://stackoverflow.com/a/4361358/10982972

You can share token it query param by first getting it via a get api that can have that authorization header.

Refer to :-

https://stackoverflow.com/a/39816150/10982972

If you think its not safe for websocket to have token in url, refer here :-

https://support.ably.com/support/solutions/articles/3000075120-is-it-secure-to-send-the-access-token-as-part-of-the-websocket-url-query-params-

Resons of not having it by official maintainer of Chromme's Websocket :-

https://github.com/whatwg/html/issues/3062#issuecomment-332065542

You can achieve addition of header by some other client like stompJS.

like here :- https://github.com/stomp-js/ng2-stompjs/issues/83#issuecomment-421210171

and an complete example with spring boot backend is available here :-

https://www.javaguides.net/2019/06/spring-boot-angular-8-websocket-example-tutorial.html

like image 127
Aakash Garg Avatar answered May 08 '26 23:05

Aakash Garg