GAE: NodeJS Express code to require Google Authentication for Access to App endpoints
To require Google Account authentication before accessing URLs in a Node.js application using the Express framework, you can use the Google OAuth 2.0 strategy. This approach uses the Passport.js library with the Google OAuth 2.0 strategy to authenticate users via their Google Accounts. This code ensures that users must authenticate with their Google Account before accessing the protected content.
Steps to Implement Google Account Authentication:
-
Install dependencies: You will need several packages to enable Google OAuth authentication. Run the following command to install them:
npm install express passport passport-google-oauth20 express-session dotenv -
Create a Google OAuth 2.0 client:
-
Go to the Google Cloud Console
-
Create a new project and enable the "Google+ API" or "Google Identity" API.
-
Create OAuth credentials and set the redirect URI to http://localhost:3000/auth/google/callback.
-
Take note of your Client ID and Client Secret.
-
-
Create a .env file: Add the following environment variables to a .env file:
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_CALLBACK_URL=http://localhost:3000/auth/google/callback
SESSION_SECRET=your-session-secret -
Create the Node.js Express app with Passport.js and Google OAuth:
require('dotenv').config(); const express = require('express'); const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth20').Strategy; const session = require('express-session');
// Initialize Express app const app = express();
// Configure session middleware app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: true, }));
// Initialize Passport and session app.use(passport.initialize()); app.use(passport.session());
// Configure Passport with Google OAuth 2.0 strategy passport.use(new GoogleStrategy({ clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: process.env.GOOGLE_CALLBACK_URL, }, (accessToken, refreshToken, profile, done) => { // In a real app, you'd likely save the user information in a database return done(null, profile); }));
// Serialize and deserialize user (for session support) passport.serializeUser((user, done) => { done(null, user); });
passport.deserializeUser((user, done) => { done(null, user); });
// Middleware to check if user is authenticated function isAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/auth/google'); }
// Routes
// Home route (public) app.get('/', (req, res) => { res.send('<h1>Welcome to the public page!</h1><a href="/protected">Go to protected page</a>'); });
// Protected route (requires login) app.get('/protected', isAuthenticated, (req, res) => { res.send(`<h1>Welcome, ${req.user.displayName}!</h1><a href="/logout">Logout</a>`); });
// Google OAuth login route app.get('/auth/google', passport.authenticate('google', { scope: ['profile'] }) );
// Google OAuth callback route app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }), (req, res) => { // Successful authentication, redirect to protected route res.redirect('/protected'); } );
// Logout route app.get('/logout', (req, res) => { req.logout(() => { res.redirect('/'); }); });
// Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Explanation of Key Components:
-
passport.use(new GoogleStrategy(...)): Configures the Google OAuth 2.0 strategy with the client ID, secret, and callback URL from your .env file. This sets up the flow for Google OAuth.
-
serializeUser and deserializeUser: These methods store and retrieve user information from the session, allowing Express to keep track of the user between requests.
-
isAuthenticated middleware: This function ensures that a user is logged in. If the user isn’t authenticated, they are redirected to the Google login page.
-
/auth/google: Redirects users to Google to log in with their Google Account.
-
/auth/google/callback: This route is called by Google after the user successfully authenticates, redirecting them to the protected content.
Routes:
-
/: A public page anyone can access.
-
/protected: A protected page that requires users to log in with a Google Account. If they aren’t authenticated, they’re redirected to the Google login page.
-
/auth/google: Initiates the Google authentication process.
-
/auth/google/callback: Handles the callback from Google after a successful login.
-
/logout: Logs the user out of the app.
Resources:
-
Passport.js Google OAuth Documentation:
Passport.js Google OAuth Strategy
(http://www.passportjs.org/packages/passport-google-oauth20/) -
Google Cloud OAuth Setup:
Google Cloud OAuth 2.0 Setup
(https://developers.google.com/identity/protocols/oauth2)
-