How to add LOGIN with Google in your WEBAPPS using Passport
Tags: beginners, programming, devops, frontend
Published: 2024-04-20 10:18:09

**_To add Google login to your web application using Passport.js, you'll need to follow these general steps:
_**
1. **Set up a Google Developer Console project:**
   - Go to the Google Developer Console (https://console.developers.google.com/).
   - Create a new project.
   - Navigate to "OAuth consent screen" under "OAuth 2.0 Client IDs" and configure your OAuth consent screen with the necessary details.
   - Go to "Credentials" and create a new OAuth 2.0 Client ID. Select "Web application" as the application type.
   - Add the authorized redirect URI for your application (e.g., http://localhost:3000/auth/google/callback).

2. **Install Passport and Passport Google OAuth Strategy:**
   ```bash
   npm install passport passport-google-oauth20
   ```

3. **Configure Passport in your application:**
   - Initialize Passport and set up the Google OAuth 2.0 Strategy in your server file (e.g., `app.js` or `server.js`).
   - Use your Google Client ID and Client Secret obtained from the Google Developer Console.

   ```javascript
   const passport = require('passport');
   const GoogleStrategy = require('passport-google-oauth20').Strategy;

   passport.use(new GoogleStrategy({
       clientID: GOOGLE_CLIENT_ID,
       clientSecret: GOOGLE_CLIENT_SECRET,
       callbackURL: '/auth/google/callback'
   },
   (accessToken, refreshToken, profile, done) => {
       // Save user profile to your database or retrieve an existing user
       return done(null, profile);
   }));

   passport.serializeUser((user, done) => {
       done(null, user);
   });

   passport.deserializeUser((user, done) => {
       done(null, user);
   });
   ```

4. **Set up routes for authentication:**
   - Define routes for handling Google authentication and callback.

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

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

5. **Protect your routes:**
   - Use Passport's `authenticate` method to protect routes that require authentication.

   ```javascript
   function ensureAuthenticated(req, res, next) {
       if (req.isAuthenticated()) {
           return next();
       }
       res.redirect('/login');
   }

   app.get('/profile', ensureAuthenticated, (req, res) => {
       res.render('profile', { user: req.user });
   });
   ```

6. **Configure sessions (optional):**
   - If you want to use sessions to persist authentication state, configure Express session middleware and Passport session middleware.

   ```javascript
   app.use(session({
       secret: 'your_secret_key',
       resave: false,
       saveUninitialized: true
   }));

   app.use(passport.initialize());
   app.use(passport.session());
   ```

7. **Add a "Login with Google" button to your frontend:**
   - Create a button that redirects the user to `/auth/google` to initiate the OAuth flow.

8. **Run your application:**
   - Start your server and test the Google login functionality.