初始连接时将JWT传递到Authorization标头中的Node.js WebSocket [英] Passing JWT to Node.js WebSocket in Authorization header on initial connection
问题描述
我正在设置一个Node.js服务器以与WebSockets通讯到我的Web应用程序.我打算使用JSON Web令牌将访问权限限制为仅已通过我们的webapp进行身份验证的用户.在研究时,我很难找到支持Authorization
标头的客户端设置并在初始连接调用上使用它的Node.js的WebSocket包?
I'm setting up a Node.js server to communicate with WebSockets to my web app. I was planning on using JSON Web Tokens to limit access to only users who have already authenticated with our webapp. While researching, I am having trouble finding a WebSocket package for Node.js that supports client-side setting of the Authorization
header and using that on the initial connection call?
我经常看到通过查询参数传递令牌的建议,这可能比通过Authorization
标头传递令牌的安全性低.我想念什么吗?是否有任何良好且维护良好的WebSocket库可用于设置客户端的Authorization
标头,以便防止不必要的服务器连接?
I regularly see recommendations to pass the token via query param, which could be less secure than passing the token via the Authorization
header. Am I missing something? Are there any good, well-maintained WebSocket libraries that allow setting the Authorization
header client-side so that I can prevent unwanted connections to the server?
推荐答案
基于浏览器的WebSocket API 无法指定HTTP标头.另一方面,查询参数方法行得通,而且还不错(当通过HTTPS使用时),因此通常被代替使用.
Browser-based WebSocket API does not make it possible to specify HTTP headers. On the other hand, the query param approach works and is not that bad (when used over HTTPS), so it's often used instead.
尽管有一些Node.js的WebSocket实现可以指定HTTP标头,但这仅在Node.js中运行客户端时有效.在浏览器中运行时不起作用.
Although there are WebSocket implementations for Node.js that make it possible to specify HTTP headers, this only works when running the client in Node.js. It doesn't work when running in a browser.
Einaros的 ws
就是这样的一个例子.在Node.js中运行时,通过Authorization
头传递JWT令牌很简单:
Einaros' ws
is one such example. Passing a JWT token via Authorization
header is simple when running in Node.js:
var WebSocket = require("ws");
' does not work in browsers
var token = "Replace_this_with_your_JWT_token";
var options = {
headers: {
"Authorization" : "JWT " + token
}
};
var ws = new WebSocket("wss://example.com/path", options);
...
但是从Browserify中使用时,要求ws
只是返回无法传递自定义标头的基于浏览器的普通WebSocket API.除非网络浏览器添加了对传递标头的支持,否则通过查询参数传递是必经之路.
But when used from Browserify, requiring ws
simply returns the ordinary browser-based WebSocket API that is unable of passing custom headers. And unless web browsers add support for passing headers, passing via the query param is the way to go.
这篇关于初始连接时将JWT传递到Authorization标头中的Node.js WebSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!