使用passport-google-oauth20时自动登录

时间:2017-11-24 00:49:10

标签: node.js cookie-session passport-google-oauth2

我遵循了一个课程,它使用护照,passport-google-oauth20,cookie-session实现了用户身份验证,一切正常(登录,注销,会话处理)但是当我发送登录/注册请求时它不会询问/提示谷歌身份验证窗口输入凭据,它始终使用相同的帐户登录。

以下是护照策略配置:

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const mongoose = require('mongoose');
const keys = require('../config/keys');

const User = mongoose.model('users');

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id).then(user => {
    done(null, user);
  });
});

passport.use(
  new GoogleStrategy(
    {
      clientID: keys.googleClientID,
      clientSecret: keys.googleClientSecret,
      callbackURL: '/auth/google/callback',
      proxy: true,
      authorizationParams: {
        access_type: 'offline',
        approval_prompt: 'force'
      }
    },
    async (accessToken, refreshToken, profile, done) => {
      const existingUser = await User.findOne({ googleID: profile.id })
        if (existingUser) {
          // we already have a record with the given profile ID
          return done(null, existingUser);
        }
          // we don't have a user record with this ID, make a new record!
          const user = await new User({ googleID: profile.id, name: profile.displayName }).save()
          done(null, user);
    })
);

1 个答案:

答案 0 :(得分:3)

prompt: 'select_account'添加到passport.authenticate()路由中的/auth/google中间件。

app.get('/auth/google', passport.authenticate('google', {
   scope: ['profile', 'email'],
   prompt: 'select_account'
});

访问此页面:https://developers.google.com/identity/protocols/OpenIDConnect#scope-param