PYTHON
Basic OAuth 2.0 Client Credentials Grant for API Access
Securely authenticate with an OAuth 2.0 protected API using the client credentials grant type for server-to-server communication.
import requests
import os
# Configuration (store these securely, e.g., in environment variables)
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://oauth.example.com/token")
API_BASE_URL = os.getenv("API_BASE_URL", "https://api.example.com/v1")
SCOPE = os.getenv("OAUTH_SCOPE", "read write") # Optional: define desired scopes
def get_oauth_token(client_id, client_secret, token_url, scope=None):
"""
Obtains an OAuth 2.0 access token using the Client Credentials grant.
"""
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_info = response.json()
return token_info.get("access_token")
except requests.exceptions.RequestException as e:
print(f"Error obtaining OAuth token: {e}")
print(f"Response content: {response.text if 'response' in locals() else 'N/A'}")
return None
def call_protected_api(api_url, access_token):
"""
Calls a protected API endpoint using the obtained access token.
"""
if not access_token:
print("No access token provided. Cannot call API.")
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 calling protected API: {e}")
print(f"Response content: {response.text if 'response' in locals() else 'N/A'}")
return None
# --- Main execution ---
# if __name__ == "__main__":
# access_token = get_oauth_token(CLIENT_ID, CLIENT_SECRET, TOKEN_URL, SCOPE)
# if access_token:
# print("Successfully obtained access token!")
# # Example: Call a specific endpoint
# # api_endpoint = f"{API_BASE_URL}/protected-resource"
# # data = call_protected_api(api_endpoint, access_token)
# # if data:
# # print("API response:", data)
# else:
# print("Failed to obtain access token.")
How it works: This Python snippet demonstrates the Client Credentials grant flow for OAuth 2.0, commonly used for server-to-server API integrations where there's no user involvement. The `get_oauth_token` function sends a POST request to the `TOKEN_URL` with the `client_id`, `client_secret`, and `grant_type='client_credentials'`. If successful, it receives an `access_token`. This token is then used by the `call_protected_api` function, which includes it in the `Authorization` header as a Bearer token when making requests to the protected API endpoints. This ensures that the server-side application is authenticated to access the API's resources. Remember to securely manage `CLIENT_ID` and `CLIENT_SECRET`, ideally via environment variables.