PYTHON
Obtaining OAuth 2.0 Client Credentials Token
Learn how to implement the OAuth 2.0 Client Credentials flow in Python to secure server-to-server API communications without user interaction.
import requests
import os
def get_oauth_token(token_url, client_id, client_secret, scope=None):
"""
Obtains an OAuth 2.0 access token using the Client Credentials flow.
Args:
token_url (str): The OAuth 2.0 token endpoint URL.
client_id (str): The client ID provided by the OAuth provider.
client_secret (str): The client secret provided by the OAuth provider.
scope (str, optional): A space-separated string of desired scopes.
Returns:
str: The access token if successful, None otherwise.
"""
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret
}
if scope:
data["scope"] = scope
try:
response = requests.post(token_url, headers=headers, data=data)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
token_data = response.json()
access_token = token_data.get("access_token")
if not access_token:
print("Error: Access token not found in response.")
return None
return access_token
except requests.exceptions.HTTPError as e:
print(f"HTTP Error obtaining token: {e}")
print(f"Response: {response.text}")
except requests.exceptions.RequestException as e:
print(f"Request Error obtaining token: {e}")
except ValueError:
print("Error: Could not parse JSON response.")
return None
# Example Usage:
if __name__ == "__main__":
# It's best practice to store sensitive information in environment variables
TOKEN_URL = os.getenv("OAUTH_TOKEN_URL", "https://example.com/oauth/token")
CLIENT_ID = os.getenv("OAUTH_CLIENT_ID", "your_client_id")
CLIENT_SECRET = os.getenv("OAUTH_CLIENT_SECRET", "your_client_secret")
API_SCOPE = os.getenv("OAUTH_API_SCOPE", "read write")
token = get_oauth_token(TOKEN_URL, CLIENT_ID, CLIENT_SECRET, API_SCOPE)
if token:
print(f"Successfully obtained token: {token[:30]}...")
# Use the token to make subsequent API calls
# For example:
# api_response = requests.get("https://example.com/api/data", headers={"Authorization": f"Bearer {token}"})
# print(api_response.json())
else:
print("Failed to obtain OAuth token.")
How it works: This Python snippet demonstrates the OAuth 2.0 Client Credentials flow, used for server-to-server communication where applications authenticate themselves rather than a user. It sends a POST request to the OAuth provider's token endpoint with the `client_id` and `client_secret` to obtain an access token. This token can then be used in subsequent API requests by including it in the `Authorization` header as a Bearer token, securing access to protected resources.