简体   繁体   English

jwt.decode() 卡住而不是在格式错误的令牌上返回错误

[英]jwt.decode() stuck instead of returning an error on malformed token

On an express nodejs server I try to validate a token with the jsonwebtoken package (v8.5.1).在 express nodejs 服务器上,我尝试使用jsonwebtoken包 (v8.5.1) 验证令牌。 I experience something really odd and don't seem to find a solution for this.我遇到了一些非常奇怪的事情,似乎没有找到解决方案。

Whenever I try to verify a malformed token the jwt.verify method becomes stuck instead of throwing the usual error which I expected.每当我尝试验证格式错误的令牌时, jwt.verify 方法就会卡住,而不是抛出我预期的常见错误。 Can someone please point out what I am doing wrong.有人可以指出我做错了什么。 Underneath you'll find the code which becomes completely stuck.在下面你会发现完全卡住的代码。

When the token is valid, the console.log statement returns the content of the jwt.当令牌有效时,console.log 语句返回 jwt 的内容。 When it is invalid, the console.log statement is never run and the endpoint just never responds.当它无效时,console.log 语句永远不会运行,端点永远不会响应。 So for some reason, it becomes completely stuck on the jwt.verify method.所以出于某种原因,它完全停留在 jwt.verify 方法上。

 router.post('/session', async (req, res) => { try { const token = req.headers['x-auth-token']; if (!token) { return res.json(false); } const verified = jwt.verify(token, process.env.JWT_SECRET); console.log(verified); if (!verified) { return res.json(false); } return res.json(true); } catch (e) { return res.status(500); } });

Hey in that case I would suggest to use promisify and wait for the promise to throw an error.嘿,在这种情况下,我建议使用 promisify 并等待承诺抛出错误。

 const verified = await promisify(jwt.verify)(req.params.token, process.env.JWT_SECRET);

using this require statement:使用这个 require 语句:

 const { promisify } = require('util');

you can check the node.js documentation你可以查看 node.js 文档

I still don't know exactly why it behaved the way it did, but at least I found a workaround that answers immediately when the token is incorrect instead of returning nothing.我仍然不知道为什么它的行为方式如此,但至少我找到了一种解决方法,可以在令牌不正确时立即回答而不是不返回任何内容。

I added a callback to the jwt.verify function:我在 jwt.verify 函数中添加了一个回调:

 const verified = jwt.verify( token, process.env.JWT_SECRET, (err, verified) => { if (err) { return res.status(401).json('Error'); } return verified; } );

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM