无法在中间件 JWT EXPRESS 中验证令牌

Can't validate token in middleware JWT EXPRESS

我在验证 JWT 令牌时遇到问题。当我从邮递员那里发出 GET 请求时,验证不起作用。该请求可以在没有令牌的情况下工作。问题是如果我想在中间件上使用这个验证怎么办?我的代码有什么问题?

客户控制器:


    authenticate: async(req,res) => {
            var email = req.body.email
            var password = req.body.password
            let emailAuth = await customer.email_auth(email) 
            if(!emailAuth){
                return res.status(500).json({status: "Failed", message:"User not found"});
            }else if(emailAuth.password != password){
                return res.status(500).json({status: "Failed", message:"Authentication failed. Wrong password."});
            }else{
                const payload = {
                    user : emailAuth.id
                };
                // console.log(payload)
                var token = jwt.sign(payload, app.get('superSecret'),{
                    expiresIn: 60 // 1menit
                });

                // return information incl token on json
                res.json({
                    success: true,
                    message: token,
                    // token: token
                })
            }

        }

users.js :


     router.use(function(req,res,next){
            var token = req.body.token || req.query.token || req.headers['x-access-token'];

            if(token){
                jwt.verify(token, app.get('superSecret'), function(err,decoded){
                    if(err){
                        return res.json({success: false, message: 'Failed to authenticate token.'})
                    }else{
                        req.decoded = decoded
                        next()
                    }
                })
            }else{
                return res.status(403).send({ 
                    success: false, 
                    message: 'No token provided.' 
                });
            }
        }) 

app.js :


    const express = require('express');
    const jwt = require('jsonwebtoken')
    const app = express();
    const bodyParser = require('body-parser');
    const router = require('./app/routes/users')

    // Route
    app.use(bodyParser())
    app.use('/users', router)


    //// server listening
    const port = process.env.PORT || 3000;
    app.listen(port)
    console.log(`server listening at ${port}`);

您需要使用您的代码创建一个中间件并将其添加到您希望仅供登录用户访问的路由。

这是你的中间件:verifyToken

var jwt = require('jsonwebtoken');
function verifyToken(req, res, next) {
  var token = req.body.token || req.query.token || req.headers['x-access-token'];

  if(token){
    jwt.verify(token, app.get('superSecret'), function(err,decoded){
      if(err){
        return return res.status(403).send({ 
          success: false, 
          message: 'Failed to authenticate.' 
        });
      }else{
        req.decoded = decoded
        next()
      }
    })
  }else{
    return res.status(403).send({ 
      success: false, 
      message: 'No token provided.' 
    });
  }
}
module.exports.verifyToken = verifyToken;

现在,在您的 app.js 中,您可以将此 verifyToken 中间件添加到 /users 路由。

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const router = require('./app/routes/users')
const verifyToken = require('./your-middleware-path')

// Route
app.use(bodyParser())
app.use('/users', verifyToken, router)


//// server listening
const port = process.env.PORT || 3000;
app.listen(port)
console.log(`server listening at ${port}`);