Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 创建自定义passport jwt策略中间件回调_Javascript_Node.js_Passport.js - Fatal编程技术网

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

Javascript 创建自定义passport jwt策略中间件回调,javascript,node.js,passport.js,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.

我想为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);
    }
};
但每次我键入“npm start”运行应用程序时,我都会遇到以下错误:

if(request.headers[AUTH_HEADER]){ ^ TypeError:无法读取未定义的属性“headers”


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

是的,我在这里找到了答案:

首先定义战略逻辑:

 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);
        })
});
然后使用该策略”

最后导出初始化功能和中间件功能

    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一样

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

//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)=>{...});