关于http headers 在 Websockets client API 中的正确操作

2021-03-22 03:26

阅读:614

标签:html   method   str   ble   sockets   com   lan   tar   page   

由于这段时间要处理websocket一些问题,要在WebSocket连接过程中使用最基础的用户名密码验证,但是一直没有找到怎么处理,然后详细阅读了RFC6455文档,然后才知道怎么处理。当然本方最后也找到一个详细的问题描述与解决方案:HTTP headers in Websockets client API

这个原题目就是:HTTP headers in Websockets client API

解决方案是:

There is no method in the JavaScript WebSockets API for specifying additional headers for the client/browser to send. However the HTTP path ("GET /xyz"), basic auth header ("Authorization") and protocol header ("Sec-WebSocket-Protocol") can be specified in the WebSocket constructor.

The Authorization header is generated from the username and password (or just username) field of the WebSocket URI:

var ws = new WebSocket("ws://username:password@example.com")

 The above results in the following header with the string "username:password" base64 encoded:

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

 

I have tested basic auth in Chrome 55 and Firefox 50 and verified that the basic auth info is indeed negotiated with the server (this may not work in Safari).

The Sec-WebSocket-Protocol header (which is sometimes extended to be used in websocket specific authentication) is generated from the optional second argument to the WebSocket constructor:

var ws = new WebSocket("ws://example.com/path", "protocol");
var ws = new WebSocket("ws://example.com/path", ["protocol1", "protocol2"]);

 The above results in the following headers:

Sec-WebSocket-Protocol: protocol

 and

Sec-WebSocket-Protocol: protocol1, protocol2

 其实还有以下的方案:

HTTP Authorization header problem can be addressed with the following:

var ws = new WebSocket("ws://username:password@example.com/service");

 Then, a proper Basic Authorization HTTP header will be set with the provided username and password. If you need Basic Authorization, then you‘re all set.


 

want to use Bearer however, and I resorted to the following trick: I connect to the server as follows:

var ws = new WebSocket("ws://my_token@example.com/service");

 And when my code at the server side receives Basic Authorization header with non-empty username and empty password, then it interprets the username as a token.技术分享图片

关于http headers 在 Websockets client API 中的正确操作

标签:html   method   str   ble   sockets   com   lan   tar   page   

原文地址:https://www.cnblogs.com/fit/p/9496607.html

上一篇:Confluence 6 匿名访问远程 API

下一篇:C#XML


评论


亲,登录后才可以留言!