PYTHON
OAuth 2.0 Client Credentials for Server-to-Server API
Securely authenticate server-to-server API calls using the OAuth 2.0 Client Credentials flow in Python, ideal for background services accessing protected resources.
import requests
import os
def get_oauth_token(token_url, client_id, client_secret, scope=None):
"""
Retrieves an OAuth 2.0 access token using the Client Credentials flow.
"""
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 exception for HTTP errors
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 make_authenticated_api_call(api_url, access_token):
"""
Makes an API call with the obtained access token.
"""
if not access_token:
print("No access token available. Cannot make API call.")
return None
headers = {
'Authorization': f'Bearer {access_token}',
'Accept': '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 making authenticated API call: {e}")
return None
# Example Usage:
# TOKEN_URL = os.environ.get('OAUTH_TOKEN_URL', 'https://auth.example.com/oauth/token')
# CLIENT_ID = os.environ.get('OAUTH_CLIENT_ID', 'your_client_id')
# CLIENT_SECRET = os.environ.get('OAUTH_CLIENT_SECRET', 'your_client_secret')
# API_RESOURCE_URL = os.environ.get('API_RESOURCE_URL', 'https://api.example.com/protected_resource')
# SCOPE = 'read write' # Optional
# access_token = get_oauth_token(TOKEN_URL, CLIENT_ID, CLIENT_SECRET, SCOPE)
# if access_token:
# print("Access Token:", access_token)
# api_data = make_authenticated_api_call(API_RESOURCE_URL, access_token)
# if api_data:
# print("API Data:", api_data)
# else:
# print("Failed to get access token.")
How it works: This Python code snippet demonstrates the OAuth 2.0 Client Credentials flow for server-to-server API authentication. It uses the `requests` library to first obtain an access token from an authorization server using a client ID and secret. Once the token is acquired, it's used in the `Authorization` header for subsequent requests to a protected API resource, ensuring secure access without user involvement.