我有Express作为后端,我正在尝试使用Passport.js添加身份验证。 我想通过密码进行身份验证 - 以及位于/ config / main命名密钥中的唯一密码:
我可以通过/ authenticate发送POST请求来生成JWT, 但我无法使用该JWT访问该应用程序,并且我在Postman中使用未经授权的方式获得了ERROR 401。 我的档案:
passport.js
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var LocalStrategy = require('passport-local');
var config = require('./main');
var pass = config.key;
// Setup work and export for the JWT passport strategy
module.exports = function(passport) {
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = config.secret;
// opts.issuer = "accounts.examplesoft.com";
// opts.audience = "yoursite.net";
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
if (jwt_payload.key === pass) {
return done(null, password);
} else {
return done(null, false);
// or you could create a new account
}
}));
};
app.js
// Initialize passport for use
app.use(passport.initialize());
// Bring in defined Passport Strategy
require('./config/passport')(passport);
var mainConfig = require('./config/main');
var key = mainConfig.key;
var pass = mainConfig.password;
// Authenticate the user and get a JSON Web Token to include in the header of future requests.
router.post('/authenticate', function(req, res) {
var token = jwt.sign({
key:'pass'
}, mainConfig.secret, { expiresIn: '24h' });
res.json({ success: true, token: 'JWT ' + token });
// Enable CORS from client-side
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
router.get('/home', passport.authenticate('jwt', { session: false }), function(req, res) {
});
// Set url for API group routes
app.use('/react', router);
我做错了什么?请让我知道,以便我可以改进我的代码并进一步浏览我的网站。我是认证功能的新手,所以请解释我做错了什么。
答案 0 :(得分:2)
修正了它! 问题是我得到的回应是:
{ “成功”:是的, “令牌”:“智威汤逊eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJwYXNzIiwiaWF0IjoxNDg0NDE1MzA4LCJleHAiOjE0ODQ1MDE3MDh9.Wb00qRygYnrpFTx2zs6o037i3UNiwRtmrrXFVhVYM04” }
我在没有JWT开头的情况下复制并粘贴了令牌