我正在使用Express,Mongoose,Passport和JWT實施授權功能。獲取「錯誤」:「未知的身份驗證策略」jwt 「」
我可以註冊一個用戶。我能夠驗證並生成JWT,我可以在JWT網站上解析JWT,但出於某種原因,我收到了未知的驗證策略錯誤消息。
我有一個Plunker實例奠定了我所有的代碼塊在:
https://plnkr.co/edit/ZNjQwcZ4rMymzBXNy5nX?p=catalogue
這裏是我的passport.js文件,其中包括我的策略:
var JwtStrategy = require('passport-jwt').Strategy;
// load up the user model
var User = require('../models/user');
var config = require('../config/database'); // get db config file
module.exports = function(passport) {
var opts = {};
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({id: jwt_payload.id}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};
這裏是我的authentication.js文件的樣子:
var express = require('express');
var router = express.Router();
var jwt = require('jwt-simple');
var config = require('../config/database');
var User = require('../models/user');
router.route('/')
.post(function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err)
res.send(err);
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
module.exports = router;
這裏是我打電話是產生錯誤的端點:
var express = require('express');
var router = express.Router();
var jwt = require('jwt-simple');
var config = require('../config/database');
var passport = require('passport');
var User = require('../models/user');
router.route('/')
.get(passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
module.exports = router;
感謝您的建議,但沒有奏效。我在var passport = require('passport')下面添加了require('./ passport'); – cnak2
我有我所有的代碼塊設置Plunker給你一個更好的看法,如果你有機會:https://plnkr.co/edit/ZNjQwcZ4rMymzBXNy5nX?p=catalogue – cnak2
仍然**護照**缺少,因爲我們是談論https://github.com/jaredhanson/passport。您應該要求護照模塊的護照,而不是提供策略 –