Google OAuth 2.0 for Web Applications

Step-by-step guide to implementing Google OAuth 2.0 in a web application with Authorization Code flow, scopes, and token handling.

Real-World Flows

Detailed Explanation

Google OAuth 2.0 for Web Apps

Google's OAuth 2.0 implementation follows the standard Authorization Code flow with some Google-specific endpoints and conventions. This guide walks through the complete implementation for a server-side web application.

Google OAuth 2.0 Endpoints

Endpoint URL
Authorization https://accounts.google.com/o/oauth2/v2/auth
Token https://oauth2.googleapis.com/token
User Info https://www.googleapis.com/oauth2/v2/userinfo
Token Revocation https://oauth2.googleapis.com/revoke
Discovery Document https://accounts.google.com/.well-known/openid-configuration

Step 1: Create OAuth Credentials

  1. Go to Google Cloud Console > APIs & Services > Credentials
  2. Create an "OAuth 2.0 Client ID" for "Web application"
  3. Add authorized redirect URIs (e.g., https://yourapp.com/auth/google/callback)
  4. Save the client_id and client_secret

Step 2: Authorization Request

https://accounts.google.com/o/oauth2/v2/auth
  ?client_id=YOUR_CLIENT_ID
  &redirect_uri=https://yourapp.com/auth/google/callback
  &response_type=code
  &scope=openid%20email%20profile
  &state=RANDOM_STATE
  &access_type=offline
  &prompt=consent

Google-specific parameters:

  • access_type=offline — Request a refresh token
  • prompt=consent — Force the consent screen (needed for refresh token on re-authentication)

Step 3: Handle Callback

// Verify state parameter
// Exchange code for tokens
const response = await fetch("https://oauth2.googleapis.com/token", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({
    code: authorizationCode,
    client_id: CLIENT_ID,
    client_secret: CLIENT_SECRET,
    redirect_uri: REDIRECT_URI,
    grant_type: "authorization_code",
  }),
});

const { access_token, refresh_token, id_token } = await response.json();

Step 4: Get User Information

const userInfo = await fetch(
  "https://www.googleapis.com/oauth2/v2/userinfo",
  { headers: { Authorization: `Bearer ${access_token}` } }
).then(r => r.json());

// userInfo: { id, email, verified_email, name, picture, locale }

Common Google OAuth Scopes

Scope Access
openid OpenID Connect (required)
email User's email address
profile Name, picture, locale
https://www.googleapis.com/auth/drive.readonly Read Google Drive files
https://www.googleapis.com/auth/calendar.events Manage calendar events
https://www.googleapis.com/auth/gmail.readonly Read Gmail messages

Use Case

A web application that allows users to 'Sign in with Google'. The app redirects users to Google's authorization page, receives an authorization code on callback, exchanges it for tokens, and fetches the user's profile information to create or update their account.

Try It — OAuth 2.0 Flow Visualizer

Open full tool