node.js 护照本地与节点-jwt-simple
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20228572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passport-local with node-jwt-simple
提问by cgiacomi
How can I combine passport-local to return a JWT token on successful authentication?
如何在成功身份验证时结合本地护照以返回 JWT 令牌?
I want to use node-jwt-simpleand looking at passport.jsI am not sure how to go about.
我想使用node-jwt-simple并查看passport.js我不知道该怎么做。
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
Is it possible to return the token when calling done() ? Something like this... (just pseudo code)
调用 done() 时是否可以返回令牌?像这样......(只是伪代码)
if(User.validCredentials(username, password)) {
var token = jwt.encode({username: username}, tokenSecret);
done(null, {token : token}); //is this possible?
}
If not, how can I return the token?
如果没有,我如何返回令牌?
回答by cgiacomi
I figured it out!
我想到了!
First of all you need to implement the correct strategy. In my case LocalStrategy, and you need to provide your validation logic. For example sake let's use the one in passport-local.
首先,您需要实施正确的策略。就我而言,LocalStrategy,您需要提供验证逻辑。例如,让我们使用护照本地中的那个。
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
the verify call back you provide function(username, password, done)will take care of finding your user and checking if the password matches (beyond the scope of the question and my answer)
您提供的验证回调function(username, password, done)将负责查找您的用户并检查密码是否匹配(超出了问题和我的回答的范围)
passport.js expects several pieces for it to work, one is that you return the user in the strategy. I was trying to change that part of the code, and that was wrong. The callback expects falseif the validation fails and an object(the validated user) if you are successful.
passport.js 需要几个部分来让它工作,一个是你在策略中返回用户。我试图更改代码的那部分,这是错误的。false如果验证失败,则回调预期,如果object成功则返回(已验证的用户)。
Now.... how to integrate JWT?
现在......如何集成JWT?
In your login route you will have to handle a successful auth or an unsuccessful one. And it is here that you need to add the JWT token creation. Like so:
在您的登录路径中,您必须处理成功或不成功的身份验证。在这里,您需要添加 JWT 令牌创建。像这样:
(remember to disable the session, otherwise you will have to implement the serialize and deserialize functions. And you don't need those if you are not persisting the session, which you are not if you are using a token based auth)
(请记住禁用会话,否则您将必须实现序列化和反序列化功能。如果您不保留会话,则不需要这些功能,如果您使用基于令牌的身份验证,则不需要这些功能)
From passport-local examples: (with the JWT token added)
来自护照本地示例:(添加了 JWT 令牌)
// POST /login
// This is an alternative implementation that uses a custom callback to
// achieve the same functionality.
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err) }
if (!user) {
return res.json(401, { error: 'message' });
}
//user has authenticated correctly thus we create a JWT token
var token = jwt.encode({ username: 'somedata'}, tokenSecret);
res.json({ token : token });
})(req, res, next);
});
And that is it! Now when you call /login and POST username and password (which should always be over SSL) the first code snippet above will try to find a user based on the username you provided and then check that the password matches (Of course you will need to change that to suit your needs).
就是这样!现在,当您调用 /login 和 POST 用户名和密码(应该始终通过 SSL)时,上面的第一个代码片段将尝试根据您提供的用户名查找用户,然后检查密码是否匹配(当然您需要更改它以满足您的需求)。
After that your login route will be called and there you can take care of returning an error or a valid token.
之后,您的登录路由将被调用,您可以在那里处理返回错误或有效令牌。
Hope this will help someone. And if I have made any mistakes or forgot something let me know.
希望这会帮助某人。如果我犯了任何错误或忘记了什么,请告诉我。
回答by ZeroCR
This is a great solution, I just want to add this:
这是一个很好的解决方案,我只想添加以下内容:
var expressJwt = require('express-jwt');
app.use('/api', expressJwt({secret: secret}));
I like to use "express-jwt"to validate the token.
我喜欢使用“express-jwt”来验证令牌。
btw: this article is great to learn how to handle the token in the client side, using Angular, in order to send it back with every request
顺便说一句:这篇文章非常适合学习如何在客户端使用 Angular 处理令牌,以便在每次请求时将其发回
https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
回答by Rob
Here's a boiler-plate I'm working on for specifically using api tokens only (no sessions...not that session are bad of course; just we're using token approach): https://github.com/roblevintennis/passport-api-tokens
这是我正在专门使用 api 令牌的样板(没有会话......当然不是那个会话不好;只是我们使用令牌方法):https: //github.com/roblevintennis/passport -api-tokens

