我有一个用 编写的 Web 服务器 Node/ express 使用 Passport 使用 JSON Web token (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
在 Passport 中配置对象,它按预期工作。现在我需要向这个应用程序添加网络套接字。我正在使用 ws 图书馆。这是我到目前为止所拥有的:
const wss = new WebSocket.Server({
port: 8080,
verifyClient: async (info, done) => {
// ???
done( result );
}
});
wss.on('connection', ws => {
// web socket events
});
如何使用通行证身份验证仅允许具有正确 token 的客户端连接到 Web 套接字服务器?
最佳答案
您可以 sign
带有用户 ID 的 token 或用于区分用户的任何内容
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);
然后将 token 传递给前端并使用它来初始化您的 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
});
这是许多方法之一。有一种 session 方式,但我看到您不想使用它们。此外,我不知道您是否使用 mongo,但对于任何数据库都是一样的,您只需要更改一些代码即可。
关于node.js - 如何使用带有 JWT 的 Node 、ws 和通行证来使用身份验证 Web 套接字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60010623/