requests-oauth2client
requests-oauth2client is an OAuth 2.x client for Python that leverages the popular `requests` HTTP library. It's designed to obtain, refresh, and revoke tokens from any OAuth2.x/OIDC compliant Authorization Server, supporting various grant types like Client Credentials, Authorization Code, Refresh Token, Token Exchange, JWT Bearer, Device Authorization, Resource Owner Password, and CIBA. The library simplifies OAuth2 interactions by integrating as a `requests` Auth Handler, automatically managing token lifecycle. It is currently at version 1.8.0 and receives regular updates.
Warnings
- breaking The `BearerAuth` class was removed in `v1.6.0`. Direct usage of `BearerToken` as a requests auth handler is the recommended replacement.
- breaking The parameter `bearer_token_class` in `OAuth2Client` was renamed to `token_class` in `v1.6.0`.
- breaking The parameter `url` in `ApiClient` methods (e.g., `get`, `post`) was renamed to `path` in `v1.6.0`.
- gotcha Prior to `v1.5.0`, the `expires_in` field in token responses might have been inconsistently handled (e.g., expecting `int` but receiving `str`). This was fixed to properly handle string values.
- gotcha A bug existed prior to `v1.3.0` where the token expiration leeway was reversed, potentially leading to tokens being considered valid for longer or shorter than intended.
- gotcha Sensitive client credentials (client_id, client_secret) should never be hardcoded or committed to version control. Always use environment variables or a secure secrets management system.
Install
-
pip install requests-oauth2client
Imports
- OAuth2Client
from requests_oauth2client import OAuth2Client
- ApiClient
from requests_oauth2client import ApiClient
- OAuth2ClientCredentialsAuth
from requests_oauth2client import OAuth2ClientCredentialsAuth
- OAuth2AuthorizationCodeAuth
from requests_oauth2client import OAuth2AuthorizationCodeAuth
- BearerToken
from requests_oauth2client import BearerToken
Quickstart
import os
import requests
from requests_oauth2client import OAuth2Client, OAuth2ClientCredentialsAuth
# --- Configuration (replace with your actual values or environment variables) ---
TOKEN_ENDPOINT = os.environ.get('OAUTH_TOKEN_ENDPOINT', 'https://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_BASE_URL = os.environ.get('API_BASE_URL', 'https://api.example.com')
SCOPE = os.environ.get('OAUTH_SCOPE', 'read write')
# --- Client Credentials Flow Example ---
try:
# 1. Initialize the OAuth2Client
oauth2client = OAuth2Client(
token_endpoint=TOKEN_ENDPOINT,
auth=(CLIENT_ID, CLIENT_SECRET) # Client authentication (Basic or Post)
)
# 2. Create an OAuth2ClientCredentialsAuth handler
auth_handler = OAuth2ClientCredentialsAuth(oauth2client, scope=SCOPE)
# 3. Create a requests Session and attach the auth handler
session = requests.Session()
session.auth = auth_handler
# 4. Make an authenticated API request
print(f"Attempting to fetch resource from {API_BASE_URL}/data...")
response = session.get(f"{API_BASE_URL}/data")
response.raise_for_status() # Raise an exception for HTTP errors
print("Successfully fetched data:")
print(response.json())
except requests.exceptions.RequestException as e:
print(f"An HTTP error occurred: {e}")
if e.response is not None:
print(f"Response Status: {e.response.status_code}")
print(f"Response Body: {e.response.text}")
except Exception as e:
print(f"An unexpected error occurred: {e}")