错误:401(未授权),Passport在节点中进行身份验证

时间:2017-05-09 11:55:41

标签: angularjs node.js authentication jwt passport.js

这里使用了Passport身份验证中间件,来自Login api我生成了一个jwt令牌,它被发送到标题中的API http://localhost:3030/home/但是它正在抛出

错误

  

angular.js:12587 POST http://localhost:3030/home/ 401(未经授权)。

     

angular.js:14525可能未处理的拒绝:{“data”:“Unauthorized”,“status”:401,“config”:{“method”:“POST”,“transformRequest”:[null],“transformResponse “:[null],”jsonpCallbackParam“:”callback“,”url“:”http://localhost:3030/home/“,”headers“:{”Accept“:”application / json,text / plain, / “}},” 状态文本 “:” 未授权“}

route.js

module.exports = function(app , passport){
    app.use('/login',userCtrl);
    app.use('/register',registerCtrl);
    app.use('/home', passport.authenticate('jwt', { session: false }) , homerCtrl);
};

passposrt.js

var JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt = require("passport-jwt").ExtractJwt;
var config = require('./appConfig.js');

module.exports = function(passport){
    var jwtOptions = {}
    jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeader();
    jwtOptions.secretOrKey = config.secret;
    var strategy = new JwtStrategy(jwtOptions, function(jwt_payload, next) {
        var user = users[_.findIndex(users, {id: jwt_payload.id})];
        if (user) {
            next(null, user);
        } else {
            next(null, false);
        }
    });
    passport.use(strategy); 
}

家庭控制器

var mongoose = require("mongoose");
var User = mongoose.model("user");
var express = require("express");
var jwt = require('jsonwebtoken');
var config = require('./../config/appConfig.js');

//Type 1 using router
var router = express.Router();
router.post('/' , function(req, res, next){
    var formData = req.body;   
    getUserData(formData , function(user){
        res.json({ "responseMessage" : "Home Api Sucess" });
    });
});

function getUserData(formData , cb){
    User.findOne({username : formData.username}).then(function(user){
        cb(user);
    }).catch(function(err){
        cb(err);
    });
}

module.exports = router;

登录控制器

var router = express.Router();
router.post('/' , function(req, res, next){
var formData = req.body; 
var username = req.body.username;
var password = req.body.password;

getUserData(formData , function(user){
    if(user){
        user.verifyPassword(password , function(err, isMatch){
        if(isMatch){
            var token = createToken(user);
            res.json({ "responseMessage" : "Login Sucess" , "token" :token});
        }else{
            res.json({ "responseMessage" : "Login Failed" });   
        }
    })
    }else{
        res.json({ "responseMessage" : "Login Failed" });   
    }
});
});

function createToken(user){
 var payload = {id: user.name};
    var token = jwt.sign(payload, config.secret);
    return "JWT " +token;
}

function getUserData(formData , cb){
    User.findOne({username : formData.username}).then(function(user){
        cb(user);
    }).catch(function(err){
        cb(err);
    });
}

2 个答案:

答案 0 :(得分:1)

passport.js替换

jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeader();

jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('JWT');

答案 1 :(得分:0)

您必须为每个受保护的路由发送授权标头。

使用Postman查看示例:

enter image description here

PS:你必须在登录过程中创建一个JWT令牌。

希望它可以帮到你。