Reputation: 6514
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.
Upvotes: 9
Views: 44981
Reputation: 296
You can't add custom headers for security issues and the WebSocket API doesn't support it.
What you can do instead is to pass your token in the URL like this:
new WebSocket("ws://localhost:8080/api/SocketDock?authorization=eyJhbGciOiJIUzI1...")
A more complete answer here.
Upvotes: 4
Reputation: 10979
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 :-
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
Upvotes: 29