3

我正在尝试学习 NodeJS,并在教程中看到了这三个函数/类,但无法理解它们是什么以及我们应该何时使用哪一个?

我需要同时使用本地护照和护照jwt,还是只使用其中之一?

4

2 回答 2

8

Passport是用于用户身份验证的 nodejs '连接样式中间件'。您最有可能将其视为Express中间件。要使用护照,您需要使用passport和定义您用于验证的“策略”。例如,这可能是 Facebook 或 Google 通过 oauth、SAML 或简单的 cookie。因此,要使用 Passport,您需要模块本身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('/');
  });

passport-local如果您针对存储在“本地”即应用程序数据库中的用户名和密码进行身份验证,您将使用该策略- “本地”意味着您的应用程序服务器本地,而不是最终用户本地。

passport-jwt是使用JSON Web Tokens的策略。

于 2020-07-21T11:56:10.203 回答
4

Passport Passport 是 Node.js 的认证中间件。Passport 使用策略的概念来认证请求。策略包括验证用户名和密码凭证、使用 OAuth(例如,通过 Facebook 或 Twitter)的委托身份验证或使用 OpenID 的联合身份验证。

passport-local本地身份验证策略使用用户名和密码对用户进行身份验证。该策略需要一个验证回调,它接受这些凭据并为用户提供完成的调用。

passport-jwt此模块允许您使用 JSON Web 令牌对端点进行身份验证。它旨在用于保护没有会话的 RESTful 端点。

于 2020-07-21T11:23:28.607 回答