如何从路由调用jwt验证功能?

时间:2018-01-26 12:13:34

标签: node.js express jwt

verify_jwt_token

var jwt = require('jsonwebtoken');
var config = require('./env/config.json')

module.exports = function(req,res,next) {
  var token = req.body.token || req.query.token || req.headers['x-access-token'];
    if (token) {
        console.log("----------------------------------------");
        console.log(token);
        console.log("----------------------------------------");

        console.log(config.jwt_secret);
        console.log("----------------------------------------");

    // verifies secret and checks exp
        jwt.verify(token, config.jwt_secret, function(err, decoded) {
            if (err) { //failed verification.
                return res.json({"error": true});
            }
            req.decoded = decoded;
            next(); //no error, proceed
        });
    } else {
        // forbidden without token
        return res.status(403).send({
            "error": true
        });
    }
}

路线

 var user  = require('../controller/user.controller.js');
 var token_verify = require('../../config/verify_jwt_token.js')

module.exports = function (app) {

app.route('/register_user').post(user.register);
app.route('/login').get(user.login);


app.route('/auth',token_verify).get(user.auth);


}

我想从这条路线调用j w t验证功能。我不想从控制器调用。 app.route( '/ AUTH',token_verify)获得(user.auth);从这条路线打来电话  请帮忙。 先感谢您。

1 个答案:

答案 0 :(得分:2)

这将有效:

const express = require('express')
const app = express()

function jwtVerify (req, res, next) {
  console.log('verifying token...')
  // logic
  next()
}

app
  .use(jwtVerify)
  .route('/example')
  .get((req, res) => res.json({ hello: 'World' }))

app.listen(3000)

您将遇到的问题是,中间件将针对您定义的每个路由执行,因为中间件已应用于app实例。要解决此问题,您需要使用Router。下面的快速脏示例:

app.js

const express = require('express')
const app = express()
const securedRoutes = require('./secured-routes')

function jwtVerify (req, res, next) {
  console.log('verifying token...')
  // logic
  next()
}

app.use('/secured', jwtVerify, securedRoutes)

app.listen(3000)

secured-routes.js

const express = require('express')
const router = express.Router()

router.get('/', (req, res) => res.json({ message: 'Hello from secured routes' }))

module.exports = router