无法使用护照和谷歌OAuth策略访问谷歌登录页面



我正在尝试使用Passport以使用户能够使用其Google帐户登录Web应用程序,但是我似乎无法获得我的登录路线,/auth/Google,甚至重定向到Google登录页面。我的其他路线正常工作,但我没有在控制台上遇到任何错误,但是当我去Localhost:5000/auth/google时,该页面只是悬挂,最终给出了" localhost拒绝连接"错误(我假设在此之后时间安排了(。

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

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

弄清楚了 - 真的很愚蠢。这个:

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

应该是:

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

您也可以使用原始获取路线,只需确保将回调附加到req,res。这是我的代码示例,该示例已经进行了测试...

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

这将使您的代码与其他路线更加一致。另外,您可能会注意到我在路线上使用了" .route"。这纯粹是出于链接的目的...

示例:

app.route('/login')
    .get( async (req, res) => {
        res.render('login');
    })
    .post(async (req, res) => {
        const user = new User(req.body);
        if(user.username && user.password) {
            req.login(user, (err) => {
                if (err) {
                    console.log(err);
                } else {
                    passport.authenticate('local', {successRedirect: '/secrets', failureRedirect: '/login'})(req, res);
                }
            });
        }
    });

对不起,很晚的建议。只是自己学习这个。希望这会有所帮助: - (

只需复制此代码,它不需要回调函数

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

最新更新