我有一个用node / express编写的Web服务器,该服务器使用通行证通过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套接字服务器?
您可以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,但是对于任何数据库,都一样,只需要更改一些代码即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句