首页 > 解决方案 > 无法使用护照和谷歌 oauth 策略进入谷歌登录页面

问题描述

我正在尝试使用 Passport 让用户能够使用他们的 Google 帐户登录 Web 应用程序,但我似乎无法让我的登录路径 /auth/google 甚至重定向到 Google 登录页面. 我的其他路线有效,我的控制台没有任何错误,但是当我转到 localhost:5000/auth/google 时,页面只是挂起并最终给出“localhost 拒绝连接”错误(我假设之后它已超时)。

知道会发生什么吗?我已经在另一个应用程序中成功地使用了基本完全相同的代码——我知道我还没有为完全登录设置大部分脚手架,但我认为它至少应该在此时加载谷歌登录页面。

index.js

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import passport from 'passport';
const GoogleStrategy = require('passport-google-oauth20').Strategy;

// import database from './server/src/models';
import userRoutes from './server/routes/UserRoutes';

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

passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.googleClientID,
      clientSecret: process.env.googleClientSecret,
      callbackURL: '/auth/google/callback'
    },
    (accessToken, refreshToken, profile, cb) => {
      console.log(accessToken);
    }
  )
);

app.use(cors());
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());

app.get('/', (req, res) => {
  res.send('Hello world!');
});

app.get('/auth/google', (req, res) => {
  passport.authenticate('google', {
    scope: ['profile', 'email']
  });
});

app.use('/users', userRoutes);

app.listen(PORT, () => {
  console.log(`App up on port ${PORT}`);
});

export default app;

这是完整仓库的链接: https ://github.com/olliebeannn/chatterpod

标签: node.jsexpresspassport.jsgoogle-oauthpassport-google-oauth2

解决方案


想通了 - 真是愚蠢的错误。这个:

app.get('/auth/google', (req, res) => {
  passport.authenticate('google', {
    scope: ['profile', 'email']
  });
});

应该:

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

推荐阅读