PYTHON

Secure API Authentication with OAuth 2.0 Client Credentials Flow

Authenticate server-side applications with an API using the OAuth 2.0 Client Credentials Grant flow in Python, obtaining and utilizing an access token for secure requests.

import requests
import os

# Configuration
TOKEN_URL = 'https://api.example.com/oauth/token'
API_URL = 'https://api.example.com/protected-resource'
CLIENT_ID = os.environ.get('OAUTH_CLIENT_ID', 'your_client_id')
CLIENT_SECRET = os.environ.get('OAUTH_CLIENT_SECRET', 'your_client_secret')
SCOPE = 'read write'

def get_access_token(token_url, client_id, client_secret, scope):
    """Obtains an access token using the Client Credentials grant type."""
    payload = {
        'grant_type': 'client_credentials',
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': scope
    }
    try:
        response = requests.post(token_url, data=payload)
        response.raise_for_status() # Raise an exception for HTTP errors
        return response.json()['access_token']
    except requests.exceptions.RequestException as e:
        print(f"Error obtaining token: {e}")
        return None

def call_protected_api(api_url, access_token):
    """Calls a protected API resource with the given access token."""
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Accept': 'application/json'
    }
    try:
        response = requests.get(api_url, headers=headers)
        response.raise_for_status() # Raise an exception for HTTP errors
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error calling API: {e}")
        return None

if __name__ == '__main__':
    token = get_access_token(TOKEN_URL, CLIENT_ID, CLIENT_SECRET, SCOPE)
    if token:
        print("Access Token obtained successfully.")
        data = call_protected_api(API_URL, token)
        if data:
            print("Protected resource data:", data)
        else:
            print("Failed to retrieve data from protected resource.")
    else:
        print("Failed to obtain access token.")
How it works: This Python snippet demonstrates the OAuth 2.0 Client Credentials grant flow for server-to-server API authentication. The `get_access_token` function sends a POST request to the token endpoint with `client_id`, `client_secret`, and `grant_type=client_credentials` to receive an access token. This token is then used by the `call_protected_api` function to make authorized requests to a protected resource by including it in the `Authorization` header as a Bearer token. This method is suitable for applications that need to access their own resources, not on behalf of a user.

Need help integrating this into your project?

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

Hire DigitalCodeLabs