简体   繁体   English

如何优雅地捕获节点和快递中的 jsonwebtoken 错误?

[英]How to gracefully catch jsonwebtoken errors in node & express?

Here is my verification function:这是我的验证功能:

exports.validateToken = function(req, res, next){
  var token = req.body.token;
  jwt.verify(token, config.sessionSecret, function(err, decoded) {
     if(err){
         return next(err);
     }else{

        var userToken = jwt.sign(req.body.user, config.secret,{
            expiresIn:10000
        });

        res.json({token: userToken})

    }    
  });
}

I'm expecting an error definition but I'm getting an internal server error on top of that:我期待一个错误定义,但除此之外我还收到一个内部服务器错误:

TokenExpiredError: jwt expired
at Object.JWT.verify (/Users/Developer/node_modules/jsonwebtoken/index.js:209:19)
at exports.validateToken (/Users/Developer/app/controllers/user.signing.controller.js:369:9)
at Layer.handle [as handle_request] (/Users/Developer/node_modules/express/lib/router/layer.js:76:5)
at next (/Users/Developer/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/Developer/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/Users/Developer/node_modules/express/lib/router/layer.js:76:5)

What am I doing wrong here?我在这里做错了什么?

const jwt = require('jsonwebtoken')

module.exports =  function auth (req,res,next) {
    const token =req.header('x-auth-token')
    if (!token){
        return res.status(401).send('to\'ken not found')
    }
 try{
        const decoded = jwt.decode(token,'m@hf1y')
         req.user = decoded
         next()

 }catch (e) {
     
     return  res.status(400).send('invalid token')
 }
}

Edit编辑

Warning: This is using jwt.decode and not jwt.verify .警告:这是使用jwt.decode而不是jwt.verify Since JSON Web Token can always be decoded without knowing the secret key, the previous code is only valid if it comes from a thrusted source.由于 JSON Web Token 始终可以在不知道密钥的情况下被解码,因此之前的代码仅在来自被推入的源时才有效。

for some reason the next response is not working.由于某种原因,下一个响应不起作用。 So I replaced that with the following code and everything is fine:所以我用下面的代码替换了它,一切都很好:

res.status(401).send({error:'invalid token'});

I have tried this in my code.我在我的代码中尝试过这个。 The res.locals.data helps to carry data to the calling function. res.locals.data有助于将数据传送到调用函数。

Just get the data in the calling function as res.locals.data and your problem is solved hopefully.只需将调用函数中的数据作为res.locals.data ,您的问题就有望得到解决。

if (err) {
    res.locals.data = {
        err: err.name,
        message : err.message
    }
    return next();
}

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

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