Hey there! So you’ve started dabbling in the world of web development, and now you want to let users sign in to your app using their Google accounts. Smart choice! Google OAuth2 is the standard method for enabling your users to log in securely. In this tutorial, we’ll walk through the process step-by-step, from setting up a Google project to integrating the OAuth2 flow in your web app.
Let’s dive in, shall we? 🚀
What is OAuth2?
OAuth2 is an open standard for access delegation, commonly used as a way to grant websites or applications limited access to a user’s information without exposing passwords. In simpler terms, it’s how your app opens a gate for Google’s login systems to hand over certain user data to your application securely.
Setting Up Your Google Cloud Project
- Go to the Google Cloud Console.
- Click on the Select a project dropdown at the top.
- Click the New Project button.
- Name your project (e.g.,
MyWebApp), and select an appropriate organization. - Hit the Create button.
Enabling Google API
- In the dashboard, navigate to APIs & Services > Library.
- Search for “Google Identity Services” and select it.
- Click Enable.
Setting Up OAuth 2.0 Credentials
- Go to APIs & Services > Credentials.
- Click Create Credentials and select OAuth client ID.
- Click Configure Consent Screen first if prompted.
- Choose External, then fill in the App Name, Support Email, and Developer Contact Info.
Creating OAuth Client ID
- Return to Credentials > Create Credentials > OAuth client ID.
- Select Web application as the application type.
- Give it a name (e.g.,
MyWebAppCredentials). - Under Authorized redirect URIs, add:
http://localhost:3000/auth/callback - Click Create. You’ll now get your Client ID and Client Secret.
Implementing OAuth2 in Your Web App
Installing Necessary Libraries
npm init -y
npm install google-auth-library express cookie-session
Setting Up Express Server
const express = require('express');
const { OAuth2Client } = require('google-auth-library');
const cookieSession = require('cookie-session');
const CLIENT_ID = 'YOUR_CLIENT_ID';
const CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
const REDIRECT_URI = 'http://localhost:3000/auth/callback';
const app = express();
// Configure session
app.use(cookieSession({
maxAge: 24 * 60 * 60 * 1000,
keys: ['your_random_session_key']
}));
// Set up the OAuth2 client
const oauth2Client = new OAuth2Client(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URI
);
// Authentication route
app.get('/auth/google', (req, res) => {
const url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: ['email', 'profile']
});
res.redirect(url);
});
// Callback route
app.get('/auth/callback', async (req, res) => {
const { tokens } = await oauth2Client.getToken(req.query.code);
oauth2Client.setCredentials(tokens);
const ticket = await oauth2Client.verifyIdToken({
idToken: tokens.id_token,
audience: CLIENT_ID
});
const payload = ticket.getPayload();
req.session.user = payload;
res.redirect('/profile');
});
// Profile route
app.get('/profile', (req, res) => {
if (!req.session.user) {
return res.redirect('/auth/google');
}
res.send('<h1>Hello ${req.session.user.name}</h1>');
});
app.listen(3000, () => console.log('App listening on port 3000'));
Testing Your Implementation
node index.js
Then open your browser and go to http://localhost:3000/auth/google. You’ll be redirected to Google login, and after successful authentication, you’ll land on a simple profile page that displays the user’s name. 🎉
Wrapping It All Up
And that’s it! You’ve successfully implemented Google OAuth2 login in your Node.js web app.
Recap:
- Created a project on Google Cloud Platform
- Enabled Google Identity API
- Generated OAuth2 credentials
- Built a Node.js app that lets users sign in with Google
Practice Ideas
- Show user’s profile photo and email
- Add logout functionality
- Deploy your app to Heroku or Vercel and test in production
- Use the token to fetch more Google API data (e.g. contacts or calendar)
If you run into any issues or want to share your app, feel free to connect! Keep building amazing things, and happy coding! 🚀
