简体   繁体   English

如何使用带有 JWT 的节点、ws 和通行证来使用身份验证 Web 套接字?

[英]How to use authenticate web sockets using node, ws and passport with JWT?

I have a web server written in node/express which uses passport to authenticate users with JSON Web Tokens (JWT).我有一个用node/express编写的 Web 服务器,它使用通行证通过 JSON Web 令牌 (JWT) 对用户进行身份验证。

For regular HTTP methods this is what I use:对于常规 HTTP 方法,这就是我使用的:

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

Where isLoggedIn is this function:其中isLoggedIn是这个函数:

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

The authentication itself is handled by the 'local-jwt' configuration in passport using a JWTStrategy object and it works as expected.身份验证本身由使用JWTStrategy对象的护照中的'local-jwt'配置处理,并且按预期工作。

Now I need to add web sockets to this app.现在我需要向这个应用程序添加网络套接字。 I'm using the ws library.我正在使用ws库。 Here is what I have so far:这是我到目前为止所拥有的:

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

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

How do I use the passport authentication to only allow clients with the correct token to connect to the web socket server?如何使用通行证身份验证仅允许具有正确令牌的客户端连接到 Web 套接字服务器?

You can sign the token with the user's id or anything you are using to differentiate users您可以使用用户的 ID 或用于区分用户的任何内容对令牌进行sign

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

then pass the token to the frontend and use it to initialize your Websocket connection with it appended to the url then take and decode it in the server like this然后将令牌传递给前端并使用它来初始化您的 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
});

This is one of many ways.这是许多方法之一。 There is a way with sessions but I see you don't want to use them.有一种会话方式,但我看到您不想使用它们。 Also I don't know if you use mongo but it's the same for any database you just have to change some code.此外,我不知道您是否使用 mongo,但对于任何数据库都是一样的,您只需要更改一些代码即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在jwt中使用护照 - How to use passport with jwt Passport-jwt身份验证无法与node-jwt-simple一起正常工作 - Passport-jwt authenticate not working well with node-jwt-simple 如何用passport-jwt验证路由? - How to authenticate a route with passport-jwt? 护照认证 jwt 没有响应 - Passport authenticate jwt not responding 如何使用 node 和 express-ws 在 websockets 中进行身份验证 - How to authenticate in websockets, using node and express-ws 您如何在 Web 应用程序中使用护照在 Facebook 上进行身份验证? - How do you authenticate on facebook using passport in a web application? 如何将Json Web Token(JWT)和Google oauth结合使用passwordjs,passport-google-oauth和node来创建社交登录系统? - How to combine Json Web Token(JWT) and google oauth using passportjs, passport-google-oauth and node to create social login system? 如何使用Socketio-jwt node.js对用户进行身份验证 - How to Authenticate user using Socketio-jwt node.js 如何使用 JWT 和 Passport 正确使用 nodeJs API 的身份验证? - How to correctly use the authentication for nodeJs API using JWT and Passport? 如何将节点快递与护照提供者和jwt结合在一起? - How to combine node express with passport providers and jwt?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM