【问题标题】:Google OAuth Broken After Heroku DeploymentHeroku 部署后 Google OAuth 中断
【发布时间】:2018-12-16 21:41:55
【问题描述】:

我的 Google OAuth 策略在客户端完美运行。但是,在将项目部署到 heroku 之后,一旦 google 尝试将用户重定向回指定的重定向路由,OAuth 就会中断。我在“/auth/google/callback/”路由上收到“请求超时”错误,这是谷歌在身份验证后将用户发送回的路由。它在我的 authRoutes 中定义(下面的屏幕截图)。我在后端使用 PassportJS 和 Express。我的开发密钥已正确设置,我的 Google OAuth 路由也已正确设置,该错误仅在来自 Google 的重定向时发生。任何帮助将不胜感激

这是我的护照策略:

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

const User = mongoose.model('users')

// This will store a cookie containing the user ID
// in our session after login is complete
passport.serializeUser((user, done) => {
    done(null, user.id);
  });

  // This is called during every request
  // It obtains a user object from the user id we serialized earlier
  // the user object is stored in req.user

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
    },
    async (accessToken, refreshToken, profile, done) => {
         const existingUser = await User.findOne({googleID: profile.id});

        if(!existingUser) {
            const user = await User.create({googleID: profile.id}).save()
            return done(null, user)
        }

        done(null, existingUser)


    })
)    

这是我的路线:

const passport = require('passport')

module.exports = app => {

// This handles getting authentication details
// (gmail profile) from google
app.get("/auth/google", passport.authenticate('google', {
    scope: ['profile', 'email']
}))

app.get("/auth/google/callback", passport.authenticate('google'), (req, res) => {
    res.redirect('/surveys')
})

app.get("/api/logout",  (req, res) => {
    // Provided by passport
    req.logout()
    res.redirect('/')
})

app.get("/api/current_user", (req, res) => {
    res.send(req.user)
})

}

还有我的 Index.js:

const express = require('express');
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const passport = require('passport');
const keys = require('./config/keys');
const bodyParser = require('body-parser')
require('./models/User');
require('./models/Survey');
require('./services/passport');

mongoose.connect(keys.mongoURI);

const app = express();

app.use(
  cookieSession({
    maxAge: 30 * 24 * 60 * 60 * 1000,
    keys: [keys.cookieKey]
  })
);
app.use(bodyParser.json())
app.use(passport.initialize());

// This middleware injects a cookie in every request
// to allow us to identify the user
app.use(passport.session());

require('./routes/authRoutes')(app);
require('./routes/billingRoutes')(app);


if(process.env.NODE_ENV == "production"){
  // Express will serve up production assets 
  // like our main.js file or main.css file!
  app.use(express.static('client/build'))

  // Express will serve up the index.html file 
  // if it doesn't recognize the route
  const path = require('path')
  app.get('*', (req, res ) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
  })

}


const PORT = process.env.PORT || 5000;
app.listen(PORT);

Heroku 错误:

at=error code=H12 desc="Request timeout" method=GET path="/auth/google/callback?code=4/tgDTZZu8osZZvvMGjX4qaazb46SqNukZU6kNARY7R2enmH21cX6IfkVYSVnVHIoQ_qHaUbLttS_VGiS81KYE3D0&scope=email+profile+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile" host=cryptic-citadel-17268.herokuapp.com request_id=e8eb956d-64e4-4217-b846-91c53953e0a7 fwd="193.203.134.47" dyno=web.1 connect=0ms service=30001ms status=503 bytes=0 protocol=https

【问题讨论】:

  • 您需要扩展“OAuth 中断”
  • 请将您的错误图片复制为问题中的文本。 StackOverflow 无法索引或搜索图片。您的错误消息表明您的 OAUth 回调 URL /auth/google/callback 没有响应。状态为 503,表示 Service Unavailable,通常表示您的代码已崩溃。
  • 你是如何连接到你的数据库的? Heroku Dashboard 上的环境变量是否与您在本地的环境变量不同?您有测试数据库设置吗?
  • @Cathal 你怎么知道你的生产可以毫无问题地连接到你的生产数据库?您可以在该区域记录一些内容吗:async (accessToken, refreshToken, profile, done) => { const existingUser = await User.findOne({googleID: profile.id}); if(!existingUser) { const user = await User.create({googleID: profile.id}).save() return done(null, user) } done(null, existingUser)
  • 您已经提到在本地一切正常 - 当您被重定向回来时,您会超时。现在,当您被重定向回来时,您要做的第一件事就是查询您的数据库

标签: express heroku google-oauth


【解决方案1】:

这是您连接到数据库的方式。您已经提到一切都在您的本地主机上正常工作,但是您的生产出现错误,请在 prod 上检查这一点 - 您的连接错误可能是由于生产数据库密钥配置造成的。

passport.use (
    new GoogleStrategy({
    clientID: keys.googleClientID,
    clientSecret: keys.googleClientSecret,
    callbackURL: '/auth/google/callback',
    proxy: true
    },
    async (accessToken, refreshToken, profile, done) => {
         const existingUser = await User.findOne({googleID: profile.id});

        if(!existingUser) {
            const user = await User.create({googleID: profile.id}).save()
            return done(null, user)
        }

        done(null, existingUser)
    })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 2022-11-29
    • 2016-07-22
    • 2018-12-20
    • 2019-01-01
    相关资源
    最近更新 更多