← Back to all snippets
PYTHON

Handling Server-Side OAuth2 Authorization Code Exchange

Securely exchange OAuth2 authorization codes for access tokens on your backend using Python, preventing client-side credential exposure and managing user sessions safely.

import requests
import os

# --- Configuration (replace with your actual values) ---
CLIENT_ID = os.environ.get('OAUTH_CLIENT_ID', 'YOUR_CLIENT_ID')
CLIENT_SECRET = os.environ.get('OAUTH_CLIENT_SECRET', 'YOUR_CLIENT_SECRET')
REDIRECT_URI = 'http://localhost:5000/callback'
TOKEN_URL = 'https://accounts.google.com/o/oauth2/token' # Example: Google

def exchange_code_for_token(auth_code: str) -> dict:
    """Exchanges an authorization code for access and refresh tokens."""
    data = {
        'code': auth_code,
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'redirect_uri': REDIRECT_URI,
        'grant_type': 'authorization_code'
    }
    try:
        response = requests.post(TOKEN_URL, data=data)
        response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
        token_data = response.json()
        
        # In a real application, store token_data securely (e.g., in a database)
        # and associate it with the user's session.
        print(f"Successfully exchanged code. Access Token: {token_data.get('access_token')}")
        return token_data
    except requests.exceptions.RequestException as e:
        print(f"Error exchanging code: {e}")
        if response and response.text:
            print(f"Response content: {response.text}")
        return {}

# --- Example Usage (simulates receiving an auth code) ---
if __name__ == '__main__':
    # In a web application, 'authorization_code_from_frontend' would come from a query parameter
    # after the user grants permission (e.g., /callback?code=YOUR_AUTH_CODE).
    authorization_code_from_frontend = 'YOUR_ACTUAL_AUTH_CODE_RECEIVED_FROM_FRONTEND'
    
    if authorization_code_from_frontend != 'YOUR_ACTUAL_AUTH_CODE_RECEIVED_FROM_FRONTEND':
        tokens = exchange_code_for_token(authorization_code_from_frontend)
        if tokens:
            print("Tokens received:", tokens)
    else:
        print("Please replace 'YOUR_ACTUAL_AUTH_CODE_RECEIVED_FROM_FRONTEND' with a real code to test.")
        print(f"Make sure your CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, and TOKEN_URL are configured correctly.")
How it works: This Python snippet demonstrates the crucial server-side step in an OAuth2 authorization code flow. After a user grants permission to your application, the identity provider redirects them back to your `REDIRECT_URI` with an `authorization_code`. This code is then sent to your backend. Your backend, using this snippet, securely exchanges the `authorization_code` along with your `CLIENT_ID` and `CLIENT_SECRET` for `access` and `refresh` tokens directly with the identity provider's token endpoint. This server-to-server exchange is vital for security, as it prevents exposing your `CLIENT_SECRET` to the client-side and ensures tokens are handled in a trusted environment.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs