简体   繁体   中英

How can I get user email with passport-google-oauth20

I am trying to implement user authentication using Node.js, passport, and passport-google-oauth20. All register/login handling works fine except it cannot retrieve user email (All other data like 'displayName' or 'provider' are successfully saved into my DB but not 'email').

Could anyone help me to get user email using passport-google-oauth20?

My code:

 const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const passport = require('passport'); const passportLocalMongoose = require('passport-local-mongoose'); const session = require('express-session'); const findOrCreate = require('mongoose-findorcreate'); const GoogleStrategy = require('passport-google-oauth20').Strategy; const FacebookStrategy = require('passport-facebook').Strategy; const app = express(); app.use(express.static('public')); app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false })); app.use(bodyParser.urlencoded({ extended: true })); app.use(passport.initialize()); app.use(passport.session()); mongoose.connect('mongodb://localhost:27017/yourDB', { useNewUrlParser: true, useUnifiedTopology: true }); mongoose.set('useFindAndModify', false); const userSchema = new mongoose.Schema({ username: String, email: String, password: String, displayName: String, provider: String }); userSchema.plugin(passportLocalMongoose); userSchema.plugin(findOrCreate); const User = mongoose.model('User', userSchema); passport.use(new GoogleStrategy({ clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: 'http://localhost:3000/auth/google/cb', userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo' }, function (accessToken, refreshToken, profile, cb) { User.findOrCreate( { googleId: profile.id }, { displayName: profile.displayName, email: profile.email, provider: 'google' }, function (error, user) { return cb(error, user); }); } )); app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }) ); app.get('/auth/google/journal', passport.authenticate('google', { failureRedirect: '/register' }), function (req, res) { res.redirect('/compose'); } );

You need to look for 'emails' array instead of email. Please refer below screenshot

在此处输入图像描述

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