use*_*308 1 node.js express passport-local passport.js passport-jwt
我正在尝试学习 NodeJS 并在教程中看到了这三个函数/类,但无法理解它们是什么以及我们什么时候应该使用哪个?
Passport Passport 是 Node.js 的身份验证中间件。Passport 使用策略的概念来验证请求。策略包括验证用户名和密码凭证、使用 OAuth 的委托身份验证(例如,通过 Facebook 或 Twitter)或使用 OpenID 的联合身份验证。
Passport-local本地认证策略使用用户名和密码对用户进行身份验证。该策略需要一个验证回调,它接受这些凭据并调用完成提供用户。
Passport-jwt此模块允许您使用 JSON Web 令牌对端点进行身份验证。它旨在用于保护没有会话的 RESTful 端点。
Passport是用于用户身份验证的 nodejs“连接式中间件”。您最有可能将其视为Express中间件。要使用护照,您需要使用passport一个“策略”来定义您用来进行身份验证的内容。例如,这可以是 Facebook 或 Google 通过 oauth、SAML 或简单的 cookie。因此,使用护照,你需要require两个passport模块本身和相关的“战略”模块。
要使用“策略”,您可以使用策略构造函数来配置 passport. 文档中给出的“本地”示例在您第一次遇到时会passport显得有些晦涩,因此使用Google 示例可能会使其更容易理解:
var passport = require('passport'); // passport
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; // Youa also need to import the Google 'strategy'
// configure passport to use the Google strategy by passing the GoogleStrategy constructor to passport.use()
passport.use(new GoogleStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "http://www.example.com/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return done(err, user);
});
}
));
// now you can use passport.authenticate() with the google strategy
app.get('/auth/google',
passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));
// GET /auth/google/callback which Google send your user to after they authenticate using Oauth
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
Run Code Online (Sandbox Code Playgroud)
passport-local如果您根据“本地”存储的用户名和密码(即在您的应用程序的数据库中)进行身份验证,您将使用的策略是“本地”意味着您的应用程序服务器本地,而不是最终用户本地。
passport-jwt是使用JSON Web Tokens的策略。
| 归档时间: |
|
| 查看次数: |
3367 次 |
| 最近记录: |