使用passport-jwt验证节点API [英] Authenticating node API with passport-jwt
问题描述
我正在尝试使用passport-jwt设置JWT身份验证。我想我采取了正确的步骤,但测试GET不会成功,我不知道如何调试它。
I'm trying to setup JWT authentication using passport-jwt. I think I've taken the right steps, but a test GET won't succeed and I don't know how to debug it.
这就是我所做的:
var jwtOptions = {
secretOrKey: 'secret',
issuer: "accounts.examplesoft.com", // wasn't sure what this was, so i left as defaulted in the doc
audience: "yoursite.net" // wasn't sure what this was, so i left as defaulted in the doc
};
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeader();
passport.use(new JwtStrategy(jwtOptions, function(jwt_payload, done) {
User.findOne({id: jwt_payload.sub}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
// or you could create a new account
}
});
}));
向我的用户/登录终端添加了令牌结果
Added a token result to my user /login endpoint
var jwt = require('jsonwebtoken');
// ...
exports.postLogin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) throw err;
if (!user) {
return res.send({ msg: 'Login incorrect' });
}
req.logIn(user, function(err) {
if (err) throw err;
var secretOrKey = jwtOptions.secretOrKey;
var token = jwt.sign(user, secretOrKey, {
expiresIn: 631139040 // 20 years in seconds
});
res.send({ user: user, jwtToken: "JWT " + token });
});
})(req, res, next);
};
事情看起来很顺利。我可以登录用户(使用护照本地身份验证),我希望回复...
Things were looking good up to here. I can login a user (using passport local auth) and the response was a I hoped...
{
user :{
_id:56c8b5bd80d16ef41ec705dd,
email:peachy@keen.com,
密码:$ 2a $ 10 $ zd ...等,
__ v:0,
},
jwtToken:JWT eyJ0eXAiOiJ ....等 }
{ "user": { "_id": "56c8b5bd80d16ef41ec705dd", "email": "peachy@keen.com", "password": "$2a$10$zd ... etc.", "__v": 0, }, "jwtToken": "JWT eyJ0eXAiOiJ .... etc." }
我创建了一个像这样的无保护测试路线......
I created an unprotected test route like this...
// in my routes file
app.get('/user/tokenTest', user.tokenTest);
在我的控制器中,一个简单的终点...
And in my controller, a simple endpoint...
exports.tokenTest = function(req, res) {
console.log(req.headers);
res.send("token test!!");
};
GET-ing工作正常。
And GET-ing that works fine, too.
-
但是我试着像这样保护这条路线:
But then I try to protect that route like this:
app.get('/user/tokenTest', passport.authenticate('jwt', { session: false }),
user.tokenTest);
在我这样做之后,只有悲伤。我发送了这样的请求:
After I do that, nothing but sadness. I send a request like this:
curl -k 'https://localhost:3443/user/tokenTest' -H 'Authorization: JWT eyJ0eXAiOiJ... etc.'
总是得到401:
未经授权
Unauthorized
控制台登录控制台似乎执行,也没有登录 passport.use
策略方法。我已经调整和调整,但我有点失落。护照-jwt doc只提供了这个例子,几乎没有其他帮助。
Console logs in the controller don't seem to execute, neither does logging in the passport.use
strategy method. I've tweaked and tweaked, but I'm a little lost. The passport-jwt doc just supplies the example, and virtually no other help.
请关于我上面的错误,或者至少如何做出任何想法关于调试??
Please, any ideas about either a mistake that I'm making above, or at least how to go about debugging??
推荐答案
对于跟随我的任何可怜的灵魂:passport-jwt doc意味着auth标题应该是这样的......
For any poor soul that follows me here: the passport-jwt doc implies that the auth header should look like this...
授权:JWT JSON_WEB_TOKEN_STRING .....
Authorization: JWT JSON_WEB_TOKEN_STRING.....
这结果是误导性的(无论如何)。
That turned out to be misleading (for me, anyway).
幸运的是,感谢这篇文章我能够学习如何构建令牌。 (令牌的前缀直到第一个'。'是该方案的base64编码。前面的JWT是阻止验证工作的噪音。
Fortunately, thanks to this article I was able to learn how the token is built. (The token's prefix up to the first '.' is the base64 encoding of the scheme. That "JWT " at the front was noise that prevented the validation from working.
所以解决方法是更改用户控制器返回的令牌:
So the fix was to change the token returned by the user controller from:
res.send({ user: user, jwtToken: "JWT " + token });
更简单:
res.send({ user: user, jwtToken: token });
Phew。是这样的,或者在这么多节点包docs中解释这些东西是不是真的很糟糕?
Phew. Is it me, or is it really a bummer how inadequately these things are explained in so many node package docs??
这篇关于使用passport-jwt验证节点API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!