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

Posted fit

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于http headers 在 Websockets client API 中的正确操作相关的知识,希望对你有一定的参考价值。

由于这段时间要处理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:[email protected]")

 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:[email protected]/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://[email protected]/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 中的正确操作的主要内容,如果未能解决你的问题,请参考以下文章

websocke 在线测试地址

websocke 在线测试地址

关于Http请求header之Referer讲解

HTTP协议关于Header

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

java代码编辑器 pdf文件预览 主流SSM 代码生成器 shrio redis websocke