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
- You have a valid Google OAuth2 access token.
- You know your Client ID (from your Google Cloud project).
- You have a programming environment set up (e.g., Python, Node.js, PHP) with libraries for making HTTP requests.
Step-by-step Guide
- Verify the Token Format
Ensure your access token is a valid JSON Web Token (JWT). It should look something like this:
eyJhbGciOiJSUzI1NiIsImtypCI6IkEyNDhFMDM3QjYxRkEwMzcwN0U4QjZGRTZDMUE2MjA5NzYzNjAwOTc3MTg3ODQyNTQyNDkxOTYxNzQzNzI1NzAyOTUiLCJ0eXAiOiJKV1QiLCJleHAiOjE2OTcwMzU4MDAsImlhdCI6MTY5NzA3MjIwMCwianRpIjoiMjk3ZmM3ODc4ZDk2NDQzNmI2YzFhNzQxZmUxZjA0OWJiNjVjNTg1OGEifYou can decode it using online JWT decoders (e.g., jwt.io) to check its claims.
- 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. - 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)); - 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 (usuallyhttps://accounts.google.comoraccounts.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.
- Validate Token Claims
Crucially, verify the following:
- Audience (aud): Check that
audmatches your Client ID. This confirms the token is intended for your application. - Issuer (iss): Ensure
issis a valid Google issuer. - Expiration Time (exp): Verify the token hasn’t expired. Compare
expto 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}") - Audience (aud): Check that
Important Considerations
- Security: Always validate the token on your server-side. Never trust client-side validation alone.
- Error Handling: Implement robust error handling to deal with invalid tokens, network issues, and unexpected responses from the Token Info endpoint.
- Token Revocation: Google can revoke access tokens at any time. The Token Info endpoint is your best way to detect a revoked token (it will return an error).
- Scope: Check the scopes associated with the token if you require specific permissions from the user. This information isn’t directly available in the Token Info response, but it was part of the original authorization request. You may need to store this information when you initially receive the access token.