[英]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.