带有授权标头的 Websocket 连接

Mur*_*bul 0 header websocket jwt angular

我正在开发一个实时 websocket 应用程序,其中服务器使用 .Net 核心进行编码,而客户端可以使用多种不同的语言。我决定保护服务器的方式是 JWT,即只接受来自具有有效 JWT 的请求的套接字连接。我可以用 .Net 客户端成功地做到这一点,这是我的代码:

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

这与 .net 核心客户端 websocket 完美配合。但是,我无法对 Angular 客户端做同样的事情。我以某种方式浏览了几篇文章,最终得到了不可能的答案。然而,在我看来,如果协议或握手在一种语言中是可能的,那么在其他语言中也必须是可能的。

有人可以指导我以正确的方式与任何 Angular 客户端实现相同的目标吗?

aak*_*arg 10

答案是 javascript 本机 websocket api 不支持添加自定义标头,因为它根本没有必要。

/sf/answers/305295091/

您可以通过首先通过具有该授权标头的 get api 获取它来共享令牌查询参数。

参考:-

/sf/answers/2787130531/

如果您认为 websocket 在 url 中包含令牌不安全,请参阅此处:-

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

Chromme 的 Websocket 的官方维护者没有拥有它的原因:-

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

您可以通过其他一些客户端(如 stompJS)实现添加标头。

像这里:- https://github.com/stomp-js/ng2-stompjs/issues/83#issuecomment-421210171

此处提供了带有 spring boot 后端的完整示例:-

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