如何使用 ExpressJS 正确设置 Passport Google OAuth 2.0?

How do I properly set up Passport Google OAuth 2.0 with ExpressJS?

我正在尝试设置一些用户身份验证并希望使用 Google 的 OAuth2.0 来执行此操作。

到目前为止,我已经在 console.cloud.google.com 建立了一个 Google API 项目并获得了一个 OAuth 2.0 客户端 ID 和客户端密码(假设 clientID = 'myID.apps.googleusercontent.com'clientSecret = 'mySecret').四处闲逛,我发现我应该使用 passport and I would like to use passport-google-oauth20 (只是因为它的下载量最多,如果有更好的东西请告诉我)。按照说明,我有:

.env.js

module.exports = {
    google: {
        clientID: 'myID.apps.googleusercontent.com',
        clientSecret: 'mySecret'
    }
}

app.js

const express = require('express')
const passport = require('passport')
const env = require('./.env.js')
const app = express()
const baseURL = 'https://api.mywebsite.com'

var GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({
    clientID: env.google.clientID,
    clientSecret: env.google.clientSecret,
    callbackURL: baseURL + "/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return cb(err, user);
    })
  }
))

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

app.get('/auth/google/callback', passport.authenticate('google', {failureRedirect: '/login'}), (req, res) => {
        // Successful authentication, redirect home.
        res.redirect('/');
    }
)

当我启动服务器并转到 https://api.mywebsite.com/auth/google 时,我被重定向到带有 Error 400: redirect_uri_mismatch 并在详细信息中引用 redirect_uri: http://127.0.0.1:5000/auth/undefined/auth/google/callbackhttps://accounts.google.com/signin/oauth/error?authError=some_mess&client_id=myID.apps.googleusercontent.com。当我检查 Google 控制台时,我明确允许授权 JavaScript 来源中的 https://api.mywebsite.com 以及所有 https://api.mywebsite.comhttps://api.mywebsite.com/auth/google/callbackhttp://127.0.0.1:5000/auth/undefined/auth/google/callback在授权重定向 URI 中。

如何正确设置这一切?

奖金:如果我想 运行 有效性检查(比如确保用户在数据库中),我该怎么做?

您可以通过以下方式正确设置google oauth2.0:

const express = require('express')
const passport = require('passport')
const googleStrategy = require('passport-google-oauth20').Strategy;
const env = require('./.env.js')
const users =require('./../database/models/User'); //change this
const app = express()

//serialize user
passport.serializeUser((user,done)=>{
    done(null,user._id);
})

//deserialize user
//on the every request deserialize function checks user whether in database
passport.deserializeUser((id,done)=>{
    users.findOne({_id:new objectId(id)},(err,doc)=>{
        if(err){return done(err)};
        if(!doc){return done(null,false)}
        return done(null,doc);
    })
})

//GOOGLE STRATEGY
passport.use(new googleStrategy({
    clientID:  env.google.clientID,
    clientSecret:env.google.clientSecret,
    callbackURL:'https://api.mywebsite.com/auth/google/callback', //change this 
    passReqToCallback   : true
},function(request,accessToken, refreshToken, profile, callback){
    users.findOneAndUpdate({profile_id:profile.id},{ 
        $setOnInsert:{
            //your data that will insert when object is not found 
        }, 
        $set:{last_login:new Date() //if user exists update this field 
        //or something you want to update
    },{
        upsert:true, //if object didn't found, insert new object to db
        new:true //return updated data
    },(err,doc)=>{
        if(err){console.log(err)}
        return callback(null, doc);
    })
}))
};