【问题标题】:How to use authenticate web sockets using node, ws and passport with JWT?如何使用带有 JWT 的节点、ws 和护照验证 Web 套接字?
【发布时间】:2023-04-03 19:10:01
【问题描述】:

我有一个用 node/express 编写的网络服务器,它使用 passport 通过 JSON Web 令牌 (JWT) 对用户进行身份验证。

对于常规的 HTTP 方法,这是我使用的:

app.get('/api/stuff', isLoggedIn(), (req, res) => {
    //get stuff
    res.send( whatever );
});

isLoggedIn 这个函数在哪里:

function isLoggedIn() {
    return passport.authenticate('local-jwt', { session: false });
}

身份验证本身由护照中的'local-jwt' 配置使用JWTStrategy 对象处理,它按预期工作。

现在我需要向这个应用程序添加网络套接字。我正在使用 ws 库。这是我目前所拥有的:

const wss = new WebSocket.Server({
    port: 8080,
    verifyClient: async (info, done) => {
        // ???
        done( result );
    }
});

wss.on('connection', ws => {
    // web socket events
});

如何使用护照身份验证仅允许具有正确令牌的客户端连接到 Web 套接字服务器?

【问题讨论】:

    标签: node.js express websocket jwt passport.js


    【解决方案1】:

    你可以sign带有用户ID的令牌或你用来区分用户的任何东西

    var today = new Date();
    var exp = new Date(today);
    exp.setDate(today.getDate() + 60);
    jwt.sign({
            id: user._id,
            exp: parseInt(exp.getTime() / 1000),
        }, secret);
    

    然后将令牌传递给前端并使用它来初始化您的 Websocket 连接,并将其附加到 url 然后像这样在服务器中获取并解码它

    const wss = new WebSocket.Server({
      verifyClient: async (info, done) => {
        console.log(info.req.url);
        console.log('------verify client------');
    
        const token = info.req.url.split('/')[1];
        var decoded = jwt.verify(token, secret);
    
        info.req.user = await User.findById(decoded.id).exec();
    
        /*info.req.user is either null or the user and you can destroy the connection
         if its null */
    
        done(info.req);
      },
      server
    });
    

    这是众多方法之一。有一种方法可以使用会话,但我看到您不想使用它们。另外我不知道你是否使用 mongo,但对于任何数据库都是一样的,你只需要更改一些代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2021-03-27
      • 2016-10-02
      • 2016-08-15
      • 2017-07-19
      • 2016-12-14
      • 1970-01-01
      相关资源
      最近更新 更多