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

134 Views Asked by At

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.

1

There are 1 best solutions below

0
On

In your '/google/callback' route, you redirect users to 'http://localhost:3000/api/auth/google' which is probably not a route registered with the react router.