创建自定义passport-jwt策略中间件回调

时间:2017-04-08 11:48:11

标签: javascript node.js passport.js

我想为passport-jwt创建一个自定义中间件来处理身份验证。

这是我创建自己的中间件所做的:

var models  = require('../models');
var passport = require("passport");  
var passportJWT = require("passport-jwt");  
var config = require("../config/config.json");  
var ExtractJwt = passportJWT.ExtractJwt;  
var Strategy = passportJWT.Strategy;  
var params = {  
    secretOrKey: config.jwtSecret,
    jwtFromRequest: ExtractJwt.fromAuthHeader()
};

/**
 * jwt authentication strategy
 */
var strategy = new Strategy(params, function(payload, done) {
    models.User.findById(payload.id)
    .then((user)=>{
        if (user) {
            return done(null, {
                id: user.id,
                username : user.username
            });
        } else {
            return done(new Error("User not found"), false);
        }
    }).catch((err)=>{
        return done(err, false);
    });
});
passport.use(strategy);

module.exports =  {  
    initialize: function() {
        return passport.initialize();
    },
    authenticate: (req, res, next)=>{
        passport.authenticate('jwt', { session: false }, (err, user, info)=>{ 
            if (err) { return next(err); } 
            if (!user) { return res.send("Custom Unauthorised").end(); } 
            // edit as per comment
            //return res.send("Test Route Accessed").end();
            req.user = user;   // Forward user information to the next middleware
            next();
        })(req, res, next);
    }
};

但每次我键入&n 39; npm start'运行应用程序我遇到这个错误:

if(request.headers [AUTH_HEADER]){            ^ TypeError:无法读取属性'标题'未定义的。

在请求中设置了授权标头。

1 个答案:

答案 0 :(得分:2)

是的我确实找到了答案:

首先定义策略逻辑:

 var strategy = new Strategy(params, function (payload, done) {
    //finding the user in the database
    console.log(payload);
    models.users.findById(parseInt(payload.userId))
        .then((user) => {
            //if the user is found
            if (user) {
                return done(null, {
                    id: user.id,
                    username: user.username
                });
            } else {
                return done(new Error("User not found"), null);
            }
        }).catch((err) => {
        console.log(err);
            return done(new Error("uncaught error! try again later"), null);
        })
});

然后让护照使用该策略“

passport.use(strategy);

最后导出初始化函数和中间件函数

    module.exports = {
    initialize: function () {
        return passport.initialize();
    },
    authenticate: function (req, res, next) {
        return passport.authenticate("jwt", {
            session: false
        }, (err, user, info) => {
            if (err) {
                console.log(err);
                return next(err);
            }
            if (!user) {
                return res.json({
                    status: 'error',
                    error: 'ANOTHORIZED_USER'
                });
            }
            // Forward user information to the next middleware
            req.user = user; 
            next();
        })(req, res, next);
    }
};

然后您可以将上面定义的函数authenticate称为路由中的中间件。

这是一个例子:

//import the express router
var express = require('express');
var router = express.Router();
//here I am importing the functions defined above, I put them in the config folder
var jwt_login_strategy = require('../config/jwt-login-strategy');
//and finally use the jwt_login_strategy as a middleware
router.post('something', jwt_login_strategy.authenticate, your_other_middleware(req, res, next)=>{...});

你必须在不添加括号的情况下调用authenticate函数,就像这个jwt_login_strategy.authenticate一样。

希望它能像我一样解决你的问题。