How can I make a button trigger the google oauth flow with passport-google-oauth20?

点点圈 提交于 2021-01-28 09:49:43

问题


I want to implement passport-google-oauth20 in my react app. I have to mention that everything work perfect on the server side, the oauth flow signs me up and creates a new user in the database. But in react it just shows a blank page and the address bar show this url, http://localhost:3000/api/auth/google

The button:

<a href='/api/auth/google'>
                <button type="submit" className="App_button _oauth">
                    <div className='socialIcon'>
                        <GoogleIcon width={18} />
                    </div>
                    <span>Sign up with Google</span>
                </button>
            </a>

google.js

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

passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => {
    User.findById(id).then(user => done(null, user));
});

module.exports = new GoogleStrategy({
    clientID: keys.GOOGLE_CLIENT_ID,
    clientSecret: keys.GOOGLE_CLIENT_SECRET,
    callbackURL: '/api/auth/google/callback',
}, async (accessToken, refreshToken, profile, done) => {
    const existingUser = await User.findOne({ googleId: profile.id });

    if (existingUser) {
        return done(null, existingUser);
    }

    const user = await new User({ 
        name: profile.displayName,
        googleId: profile.id,
    }).save();

    done(null, user);
});

google oauth routes

router.get('/google', passport.authenticate('google', { scope: ['profile', 'email'], }));
router.get('/google/callback', passport.authenticate('google'), (req, res) => {
    res.redirect('/api/auth/profile');
});
router.get('/profile', (req, res) => res.send(req.user));
router.get('/logout', (req, res) => {
    req.logout();
    res.send(req.user);
});

package.json

...
"proxy": {
    "/api/auth/google": {
      "target": "http://localhost:8080"
    },
    "/api/*": {
      "target": "http://localhost:8080"
    }
  },
...

I want to make that button trigger the oauth flow properly.

来源:https://stackoverflow.com/questions/61170364/how-can-i-make-a-button-trigger-the-google-oauth-flow-with-passport-google-oauth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!