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

时间:2018-11-12 06:11:36

标签: express jwt express-router

我对JWT令牌的验证有疑问。当我向邮递员发出GET请求时,验证不起作用。该请求不能使用令牌。问题是,如果我想在中间件上使用此验证怎么办?我的代码有什么问题?

customerController:


    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}`);

1 个答案:

答案 0 :(得分:0)

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

这是您的中间件: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}`);