Blog | G5 Cyber Security

Google OAuth2 Access Token Authentication

TL;DR

This guide shows you how to authenticate users using a Google OAuth2 access token without needing to refresh tokens or go through the full authorization flow. We’ll verify the token and extract user information.

Prerequisites

Step-by-step Guide

  1. Verify the Token Format

    Ensure your access token is a valid JSON Web Token (JWT). It should look something like this:

    eyJhbGciOiJSUzI1NiIsImtypCI6IkEyNDhFMDM3QjYxRkEwMzcwN0U4QjZGRTZDMUE2MjA5NzYzNjAwOTc3MTg3ODQyNTQyNDkxOTYxNzQzNzI1NzAyOTUiLCJ0eXAiOiJKV1QiLCJleHAiOjE2OTcwMzU4MDAsImlhdCI6MTY5NzA3MjIwMCwianRpIjoiMjk3ZmM3ODc4ZDk2NDQzNmI2YzFhNzQxZmUxZjA0OWJiNjVjNTg1OGEif

    You can decode it using online JWT decoders (e.g., jwt.io) to check its claims.

  2. Fetch the Token Info Endpoint

    Google provides an endpoint to verify and retrieve information about an access token. The URL is:

    https://oauth2.googleapis.com/tokeninfo?access_token={YOUR_ACCESS_TOKEN}

    Replace {YOUR_ACCESS_TOKEN} with your actual access token.

  3. Make the HTTP Request

    Use an HTTP client (e.g., `requests` in Python, `node-fetch` in Node.js) to make a GET request to the Token Info endpoint.

    Python Example:

    import requests
    
    token = "YOUR_ACCESS_TOKEN"
    url = f"https://oauth2.googleapis.com/tokeninfo?access_token={token}"
    response = requests.get(url)
    response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
    data = response.json()
    print(data)

    Node.js Example:

    const fetch = require('node-fetch');
    
    const token = 'YOUR_ACCESS_TOKEN';
    const url = `https://oauth2.googleapis.com/tokeninfo?access_token=${token}`;
    
    fetch(url)
      .then(res => res.json())
      .then(data => console.log(data))
      .catch(err => console.error('Error:', err));
  4. Parse the Response

    The response is a JSON object containing information about the token.

    • aud: The audience of the token (your Client ID).
    • iss: The issuer of the token (usually https://accounts.google.com or accounts.google.com).
    • exp: The expiration time of the token (in Unix timestamp seconds).
    • iat: The issue time of the token (in Unix timestamp seconds).
    • sub: The subject of the token (the user’s ID).
    • email: The user’s email address, if granted.
    • name: The user’s full name, if granted.
  5. Validate Token Claims

    Crucially, verify the following:

    • Audience (aud): Check that aud matches your Client ID. This confirms the token is intended for your application.
    • Issuer (iss): Ensure iss is a valid Google issuer.
    • Expiration Time (exp): Verify the token hasn’t expired. Compare exp to the current time.

    Python Example:

    import time
    
    current_time = int(time.time())
    if data['aud'] != 'YOUR_CLIENT_ID':
      print("Invalid audience")
    else if data['iss'] not in ['https://accounts.google.com', 'accounts.google.com']:
      print("Invalid issuer")
    else if current_time > data['exp']:
      print("Token expired")
    else:
      user_id = data['sub']
      email = data.get('email') # Email might not always be present
      name = data.get('name')
      print(f"User ID: {user_id}")
      if email:
        print(f"Email: {email}")
      if name:
        print(f"Name: {name}")

Important Considerations

Exit mobile version