Passing JWT to Node.js WebSocket in Authorization header on initial connection

前端 未结 1 1463
粉色の甜心
粉色の甜心 2021-02-13 13:00

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 authenticat

相关标签:
1条回答
  • 2021-02-13 13:33

    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.

    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 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);
    ...
    

    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.

    0 讨论(0)
提交回复
热议问题