How to Implement Google OAuth2 in a Web App
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?
First off, let’s get a little background. 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
Before you implement OAuth2, you need a Google Cloud Platform project. Here’s how to create one:
1. Go to the Google Cloud Console.
2. Click on the Select a project dropdown at the top.
3. Click the New Project button.
4. Name your project (e.g., MyWebApp
), and make sure you select an appropriate organization.
5. Hit the Create button.
Enabling Google API
With your project ready, enable the necessary APIs:
1. In the dashboard, navigate to APIs & Services > Library.
2. Search for “Google+ API” or “Google Identity Services” and select it.
3. Click Enable.
You’re halfway there. Now, it’s time to get your hands on some credentials.
Setting Up OAuth 2.0 Credentials
1. In the sidebar, go to APIs & Services > Credentials.
2. Click Create Credentials and choose OAuth client ID.
3. You’ll be prompted to configure the consent screen. Click Configure Consenet Screen.
4. Choose External, and hit Create.
5. Fill in the necessary fields, like App Name, User Support Email, and Developer Contact Info.
Creating OAuth Client ID
1. Now return to Credentials and select Create Credentials > OAuth client ID.
2. Choose Web application as the application type.
3. Enter a name like MyWebAppCredentials
.
4. Under Authorized redirect URIs, add the URL that Google will redirect to after authentication. Locally, it could be something like http://localhost:3000/auth/callback
.
5. Hit Create.
After this, Google will present you with a Client ID and Client Secret. Hang onto these, as you’ll need them soon.
Implementing OAuth2 in Your Web App
Let’s write some code, shall we?
Installing Necessary Libraries
We’ll be using Node.js for this example. First, make sure you have Node.js installed on your system. Then, create a new project and install the google-auth-library
.
bash
npm init -y
npm install google-auth-library express cookie-session
Setting Up Express Server
Here’s a simple Express setup to make your server run:
javascript
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
);
// Add authentication routes
app.get('/auth/google', (req, res) => {
const url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: ['email', 'profile']
});
res.redirect(url);
});
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');
});
app.get('/profile', (req, res) => {
if (!req.session.user) {
return res.redirect('/auth/google');
}
res.send(Hello ${req.session.user.name}
);
});
app.listen(3000, () => console.log('App listening on port 3000'));
Testing Your Implementation
Now, run your server with:
bash
node index.js
Navigate to http://localhost:3000/auth/google
in your browser. You should see the Google login screen. Upon successful login, it redirects you to a simple profile page displaying the user’s name. Neat, right?
Wrapping It All Up
And that’s a wrap! You’ve just set up Google OAuth2 authentication on your web app. This tutorial covered:
– Setting up a Google Cloud project
– Enabling the necessary APIs
– Creating OAuth2 credentials
– Configuring an Express.js server to handle authentication
Practice Ideas
– Add more attributes like profile picture or email to your profile page.
– Deploy your app on a platform like Heroku and try the login flow there.
– Play around with the Google API to pull more user data or update profile information.
Feel free to reach out if you have queries. Keep coding and having fun building those awesome projects!