_To add Google login to your web application using Passport.js, you’ll need to follow these general steps:
_
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).
Install Passport and Passport Google OAuth Strategy:
npm install passport passport-google-oauth20
-
Configure Passport in your application:
- Initialize Passport and set up the Google OAuth 2.0 Strategy in your server file (e.g.,
app.js
orserver.js
). - Use your Google Client ID and Client Secret obtained from the Google Developer Console.
- Initialize Passport and set up the Google OAuth 2.0 Strategy in your server file (e.g.,
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); });
-
Set up routes for authentication:
- Define routes for handling Google authentication and callback.
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('/'); });
-
Protect your routes:
- Use Passport’s
authenticate
method to protect routes that require authentication.
- Use Passport’s
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 }); });
-
Configure sessions (optional):
- If you want to use sessions to persist authentication state, configure Express session middleware and Passport session middleware.
app.use(session({ secret: 'your_secret_key', resave: false, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session());
Add a “Login with Google” button to your frontend:
- Create a button that redirects the user to
/auth/google
to initiate the OAuth flow.
- Create a button that redirects the user to
Run your application:
- Start your server and test the Google login functionality.