PYTHON

Implement OAuth 2.0 Client Credentials Flow

Securely obtain an access token for server-to-server API communication using the OAuth 2.0 Client Credentials Grant flow in Python.

import requests
import os

# Environment variables for sensitive information
CLIENT_ID = os.getenv('OAUTH_CLIENT_ID', 'your_client_id')
CLIENT_SECRET = os.getenv('OAUTH_CLIENT_SECRET', 'your_client_secret')
TOKEN_URL = os.getenv('OAUTH_TOKEN_URL', 'https://api.example.com/oauth/token')
SCOPE = os.getenv('OAUTH_SCOPE', 'read write') # Optional scope

def get_oauth_token():
    try:
        response = requests.post(
            TOKEN_URL,
            data={
                'grant_type': 'client_credentials',
                'client_id': CLIENT_ID,
                'client_secret': CLIENT_SECRET,
                'scope': SCOPE # Include if required by the API
            },
            headers={'Content-Type': 'application/x-www-form-urlencoded'}
        )
        response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
        token_data = response.json()
        access_token = token_data.get('access_token')
        expires_in = token_data.get('expires_in')

        if access_token:
            print(f"Successfully obtained access token: {access_token[:10]}... (expires in {expires_in} seconds)")
            return access_token
        else:
            print(f"Failed to get access token. Response: {token_data}")
            return None
    except requests.exceptions.RequestException as e:
        print(f"Error during token request: {e}")
        return None
    except ValueError:
        print(f"Error decoding JSON response for token request: {response.text}")
        return None

if __name__ == "__main__":
    token = get_oauth_token()
    if token:
        print("Token acquired. You can now use it for API calls.")
        # Example API call with the acquired token
        # API_ENDPOINT = 'https://api.example.com/data'
        # headers = {'Authorization': f'Bearer {token}'}
        # api_response = requests.get(API_ENDPOINT, headers=headers)
        # print(f"API call response status: {api_response.status_code}")
    else:
        print("Could not acquire token.")
How it works: This Python snippet demonstrates how to implement the OAuth 2.0 Client Credentials Grant flow. This flow is used for server-to-server authentication, where an application accesses its own resources or protected resources of another service without user involvement. The code sends a POST request to the token endpoint with the `client_id`, `client_secret`, and `grant_type='client_credentials'`, then extracts and returns the `access_token` from the JSON response for subsequent authenticated API requests.

Need help integrating this into your project?

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

Hire DigitalCodeLabs