在初始连接时将 JWT 传递给 Authorization 标头中的 Node.js WebSocket [英] Passing JWT to Node.js WebSocket in Authorization header on initial connection

查看:56
本文介绍了在初始连接时将 JWT 传递给 Authorization 标头中的 Node.js WebSocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设置一个 Node.js 服务器来与我的 Web 应用程序的 WebSocket 通信.我计划使用 JSON Web Tokens 来限制只有已经通过我们的 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.除非 Web 浏览器添加对传递标头的支持,否则通过查询参数传递是可行的方法.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆