简体   繁体   中英

Auto login while using passport-google-oauth20

I followed a course and it implemented user authentication using passport, passport-google-oauth20, cookie-session and it all works fine (login, logout, session handling) but when i send a request for a Log in/Sign Up it doesnt ask/prompt the google authentication window to enter the credentials, it always logs in with the same account.

Here is the passport-strategy configuration:

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);
    })
);

Add prompt: 'select_account' to the passport.authenticate() middleware in your /auth/google route.

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

Visit this page: https://developers.google.com/identity/protocols/OpenIDConnect#scope-param

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM