这里使用了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);
});
}