我正在使用 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
,refreshToken
和profile
,因此似乎是接收来自 Google 的响应,而不是callbackURL
.