1

我正在使用 Passport 并研究Google OAuth 2 strategy。我很难理解流程。

这是官方文档中的代码:

var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

// Use the GoogleStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Google
//   profile), and invoke a callback with a user object.
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);
       });
  }
));

然后是路线:

// GET /auth/google
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in Google authentication will involve
//   redirecting the user to google.com.  After authorization, Google
//   will redirect the user back to this application at /auth/google/callback
app.get('/auth/google',
  passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));

// GET /auth/google/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get('/auth/google/callback', 
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

这是我对流程的理解。用户单击按钮以在浏览器上使用 google 登录。请求被发送到/auth/google。哪个电话passport.authenticate。从那里,谷歌处理一些事情,一旦用户允许我们访问他们的谷歌账户,好吧,这就是我不理解的部分。

下一步是什么?Google 似乎会向callbackURL我们提供的内容发送回复。但在这种情况下,回调何时passport.use运行?该回调正在接受accessToken,refreshTokenprofile,因此似乎是接收来自 Google 的响应,而不是callbackURL.

4

1 回答 1

0

在您的应用程序中,当用户首次授予您通过 Google验证帐户的权限时,需要考虑两个可能的“流程”:

  • 用户在您的系统中已有一个帐户,并希望将该帐户与她的 Google 身份相关联。
  • 用户正在您的系统中创建一个新帐户,您为她提供了一个使用她的 Google 身份创建新帐户的选项

如果用户选择使用 Google 进行身份验证,最终结果是您的数据库中的一条记录,其中包含从 Google 的身份验证服务响应中提供的附加信息。数据看起来类似于护照文档中的此页面

带有令牌的对象的第一个参数的passport.use(...)调用是护照用来访问 Google 系统的方法(标准 OAUTH2 凭据)。第二个参数是与系统数据层交互的回调函数,例如:User.findOrCreate(data).

在将来访问您的应用程序时,用户可以利用他们的帐户与他们的 Google 身份“关联”这一事实,并获得简单的登录体验。

于 2019-05-27T00:07:36.467 回答