Google oauth redirect URL is react routed page. How can I use passport.authenticate middleware to extract user info?

3 min read 20-09-2024
Google oauth redirect URL is react routed page. How can I use passport.authenticate middleware to extract user info?


In the modern web development landscape, integrating authentication into your application has become an essential task. One popular method of authentication is Google OAuth. However, it can be somewhat challenging when you're dealing with a React application and need to manage user sessions and routing effectively. In this article, we will explore how to set up Google OAuth in a React application using the Passport.js library, particularly focusing on how to extract user information using the passport.authenticate middleware.

Problem Scenario

When using Google OAuth with a React routed page, you may encounter a challenge. Specifically, you need to manage the redirect URL properly so that it points to a route within your React application. Additionally, you want to utilize passport.authenticate to handle the authentication process and extract user information.

Here’s the original code snippet illustrating the problem:

app.get('/auth/google/callback', passport.authenticate('google', { 
    failureRedirect: '/' 
}), (req, res) => {
    // Successful authentication, redirect to React app
    res.redirect('/dashboard');
});

Understanding the Code

The code above handles the callback from Google after the user has authenticated successfully. The passport.authenticate middleware checks if the user has authenticated and either redirects to the specified route on failure or proceeds to redirect to the React application on success.

Step-by-Step Setup for Google OAuth with React

1. Setting up the Google Developer Console

To begin, you need to create credentials in the Google Developer Console:

  • Create a new project.
  • Navigate to "Credentials."
  • Click on "Create Credentials" and select "OAuth 2.0 Client IDs."
  • Set the redirect URI to your callback endpoint (e.g., http://localhost:5000/auth/google/callback).

2. Install Required Packages

Ensure that you have the necessary packages installed:

npm install passport passport-google-oauth20 express-session

3. Passport Configuration

In your Express server, configure Passport to use Google OAuth:

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const session = require('express-session');

// User model (you should have a User model defined in your application)
const User = require('./models/User');

passport.use(new GoogleStrategy({
    clientID: 'YOUR_GOOGLE_CLIENT_ID',
    clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET',
    callbackURL: '/auth/google/callback'
  },
  (accessToken, refreshToken, profile, done) => {
    User.findOrCreate({ googleId: profile.id }, (err, user) => {
      return done(err, user);
    });
  }
));

// Serialize and deserialize user
passport.serializeUser((user, done) => {
    done(null, user.id);
});

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

4. Setting Up Express Routes

Set up the routes that will handle authentication and the callback from Google:

app.use(session({ secret: 'your_secret', resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

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

app.get('/auth/google/callback', 
  passport.authenticate('google', { failureRedirect: '/' }),
  (req, res) => {
    // Successful authentication, redirect to the React app
    res.redirect('/dashboard');
});

5. Handling User Info Extraction

When a user successfully authenticates, Passport stores the user’s information in the session. You can access the user information like this:

app.get('/api/user', (req, res) => {
    res.send(req.user); // This will include user info if authenticated
});

Practical Example: User Experience

Once you have the above set up, when users try to access your application, they will be prompted to log in with their Google account. On successful login, they are redirected to the /dashboard route of your React application. The user information (like name and email) will be available in req.user after authentication, and you can easily render it in your React components.

Conclusion

Integrating Google OAuth with a React application using Passport.js allows you to manage user authentication efficiently. This setup not only provides a seamless login experience but also gives you the ability to extract user information directly, making it easier to personalize user experiences within your application.

Additional Resources

With this guide, you should be able to navigate the complexities of Google OAuth and provide a robust authentication system in your React application. Happy coding!