PYTHON
OAuth 2.0 Client Credentials Flow (Python)
Securely authenticate server-to-server API calls using Python with the OAuth 2.0 Client Credentials flow for automated backend access.
import requests
import os
# Configuration from environment variables for security
TOKEN_URL = os.getenv('OAUTH_TOKEN_URL', 'https://api.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')
def get_oauth_token():
"""Fetches an access token using Client Credentials Grant."""
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
payload = {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'scope': API_SCOPE
}
try:
response = requests.post(TOKEN_URL, headers=headers, data=payload)
response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
token_data = response.json()
return token_data.get('access_token')
except requests.exceptions.RequestException as e:
print(f"Error fetching OAuth token: {e}")
return None
def call_protected_api(access_token, api_url):
"""Calls a protected API endpoint with the obtained access token."""
if not access_token:
print("No access token available. Cannot call API.")
return None
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
try:
response = requests.get(api_url, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error calling protected API: {e}")
return None
if __name__ == '__main__':
# Example usage
token = get_oauth_token()
if token:
print(f"Obtained Access Token: {token[:30]}...")
# Replace with your actual protected API endpoint
PROTECTED_API_URL = os.getenv('PROTECTED_API_URL', 'https://api.example.com/data')
api_response = call_protected_api(token, PROTECTED_API_URL)
if api_response:
print("Protected API Response:")
print(api_response)
else:
print("Failed to obtain OAuth token.")
How it works: This Python snippet demonstrates the OAuth 2.0 Client Credentials Grant flow, ideal for server-to-server communication where no user interaction is involved. It first obtains an access token by sending client ID and secret to the authorization server's token endpoint. This token is then used in the 'Authorization: Bearer' header to make authenticated requests to a protected API, ensuring secure access to resources.