OAuth2Session¶
Self-refreshing OAuth 2.0 client-credentials session for HTTP API sources.
- class scamander.api.oauth2_session.OAuth2Session(token_url: str, client_id: str, client_secret: str, grant_type: str = 'client_credentials', token_refresh_margin: int = 60, cert: str | tuple[str, str] | None = None, verify: bool | str = True, scope: str | None = None)¶
Bases:
SessionA
requests.Sessionsubclass that transparently manages OAuth 2.0client_credentialstoken lifecycle.On construction the session fetches an initial access token and injects it into the
Authorization: Bearerheader. Before every subsequent HTTP request,ensure_token_validis called to refresh the token proactively when it is withintoken_refresh_marginseconds of expiry — avoiding mid-request 401 errors in long-running pipelines.- Parameters:
token_url (str) – The OAuth 2.0 token endpoint URL.
client_id (str) – Client ID issued by the authorisation server.
client_secret (str) – Client secret issued by the authorisation server.
grant_type (str) – OAuth 2.0 grant type. Defaults to
"client_credentials".token_refresh_margin (int) – Seconds before token expiry at which a proactive refresh is triggered. Defaults to
60.cert – Client-side certificate for mutual TLS. Either a path to a combined PEM file or a
(cert, key)path tuple. Applied to both API requests and the token refresh call. Defaults toNone.verify – Server certificate verification. CA bundle path,
True(default CA store), orFalse(disable). Defaults toTrue.scope (str | None) – OAuth 2.0
scopesent in the token request body. Required by Azure AD v2.0 client-credentials requests (e.g. the Microsoft Graph default scope). Omitted from the request entirely whenNone, so existing non-AAD callers are unaffected. Defaults toNone.
Example:
session = OAuth2Session( token_url="https://auth.example.com/oauth/token", client_id="my-client", client_secret="my-secret", ) response = session.get("https://api.example.com/data") # Azure AD v2.0 client-credentials flow requires a scope: graph_session = OAuth2Session( token_url=f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token", client_id=client_id, client_secret=client_secret, scope="https://graph.microsoft.com/.default", )
- ensure_token_valid()¶
Refresh the token if it’s expired or about to expire.
- refresh_token()¶
Retrieves a new OAuth 2.0 token and updates session headers.
- request(method, url, *args, **kwargs)¶
Override request to always ensure a valid token before sending.