A comprehensive Python library for implementing OAuth 1.0 and OAuth 2.0 authentication protocols
npx @tessl/cli install tessl/pypi-oauthlib@3.3.0Type stubs for oauthlib - a comprehensive Python library for implementing OAuth 1.0 and OAuth 2.0 authentication protocols. This package provides complete type definitions enabling static type checking for OAuth-enabled applications, authentication servers, and API integrations.
pip install types-oauthlibpip install oauthlib)import oauthlib
from oauthlib import oauth1, oauth2, openid, common
# Debug functions
from oauthlib import set_debug, get_debugOAuth 1.0 specific imports:
from oauthlib.oauth1 import Client, RequestValidator
from oauthlib.oauth1 import AccessTokenEndpoint, AuthorizationEndpoint, RequestTokenEndpointOAuth 2.0 specific imports:
from oauthlib.oauth2 import WebApplicationClient, BackendApplicationClient
from oauthlib.oauth2 import AuthorizationEndpoint, TokenEndpoint, ResourceEndpoint
from oauthlib.oauth2 import RequestValidator, BearerTokenOpenID Connect specific imports:
from oauthlib.openid import RequestValidator, Server, UserInfoEndpointfrom oauthlib.oauth2 import WebApplicationClient
from oauthlib.common import generate_token
import requests
# Create OAuth 2.0 client
client = WebApplicationClient('your-client-id')
# Prepare authorization request
authorization_url = 'https://auth.example.com/authorize'
url, headers, body = client.prepare_authorization_request(
authorization_url,
redirect_url='https://your-app.com/callback',
scope=['read', 'write'],
state=generate_token()
)
# User visits the authorization URL and gets redirected back with code
# Exchange authorization code for access token
token_url = 'https://auth.example.com/token'
url, headers, body = client.prepare_token_request(
token_url,
authorization_response=callback_url,
redirect_url='https://your-app.com/callback'
)
# Make token request
token_response = requests.post(url, headers=headers, data=body)
client.parse_request_body_response(token_response.text)
# Use access token to make API requests
url, headers, body = client.add_token('https://api.example.com/data')
api_response = requests.get(url, headers=headers)from oauthlib.oauth2 import WebApplicationServer, RequestValidator
class MyRequestValidator(RequestValidator):
def validate_client_id(self, client_id, request, *args, **kwargs):
# Validate the client_id
return client_id in valid_clients
def authenticate_client(self, request, *args, **kwargs):
# Authenticate the client
return request.client_id in authenticated_clients
def save_authorization_code(self, client_id, code, request, *args, **kwargs):
# Store authorization code
store_code(client_id, code, request)
# Create OAuth 2.0 server
validator = MyRequestValidator()
server = WebApplicationServer(validator)
# Handle authorization request
headers, body, status = server.create_authorization_response(
uri='https://your-server.com/authorize?response_type=code&client_id=client&redirect_uri=callback',
http_method='GET',
credentials={'user_id': 'user123'}
)The oauthlib type stubs are organized into several key modules that mirror the OAuth specification hierarchy:
This modular architecture enables developers to use specific OAuth flows while maintaining type safety and IDE support throughout the authentication process.
Complete OAuth 1.0 (RFC 5849) client and server implementation with signature methods, request/access token flows, and protected resource access. Supports HMAC-SHA1, RSA-SHA1, and PLAINTEXT signature methods.
class Client:
def __init__(
self,
client_key: str,
client_secret: str | None = None,
resource_owner_key=None,
resource_owner_secret=None,
callback_uri=None,
signature_method: str = "HMAC-SHA1",
signature_type: str = "AUTH_HEADER",
rsa_key=None,
verifier=None,
realm=None,
encoding: str = "utf-8",
decoding=None,
nonce=None,
timestamp=None,
): ...
def sign(
self,
uri: str,
http_method: str = "GET",
body: str | dict[str, str] | list[tuple[str, str]] | None = None,
headers: dict[str, str] | None = None,
realm=None,
): ...Multiple client implementations supporting all OAuth 2.0 grant types including authorization code, implicit, client credentials, and password flows. Includes PKCE support for enhanced security.
class WebApplicationClient:
def __init__(
self,
client_id: str,
default_token_placement: str = "auth_header",
token_type: str = "Bearer",
access_token: str | None = None,
refresh_token: str | None = None,
**kwargs,
): ...
def prepare_authorization_request(
self,
authorization_url: str,
state: str | None = None,
redirect_url: str | None = None,
scope: str | list[str] | None = None,
**kwargs,
) -> tuple[str, dict[str, str], str]: ...
def prepare_token_request(
self,
token_url: str,
authorization_response: str | None = None,
redirect_url: str | None = None,
state: str | None = None,
body: str = "",
**kwargs,
) -> tuple[str, dict[str, str], str]: ...Complete server-side OAuth 2.0 implementation with authorization servers, resource servers, token endpoints, and request validation. Supports all standard grant types and extensions.
class WebApplicationServer:
def __init__(self, request_validator, token_expires_in=None, token_generator=None, refresh_token_generator=None): ...
def create_authorization_response(
self,
uri: str,
http_method: str = "GET",
body: str | None = None,
headers: dict[str, str] | None = None,
scopes: list[str] | None = None,
credentials: dict[str, str] | None = None,
) -> tuple[dict[str, str], str, int]: ...
def create_token_response(
self,
uri: str,
http_method: str = "POST",
body: str | None = None,
headers: dict[str, str] | None = None,
credentials: dict[str, str] | None = None,
**kwargs,
) -> tuple[dict[str, str], str, int]: ...Token creation, validation, and formatting with support for Bearer tokens, MAC tokens, and JWT tokens. Includes token generators, validators, and utility functions for token handling.
class BearerToken:
def __init__(
self,
request_validator=None,
token_generator=None,
expires_in: int | None = None,
refresh_token_generator=None,
): ...
def create_token(self, request, refresh_token: bool = False, **kwargs) -> dict[str, str]: ...
def validate_request(self, request) -> bool: ...
class OAuth2Token(dict):
@property
def scope_changed(self) -> bool: ...
@property
def scopes(self) -> list[str]: ...
@property
def missing_scopes(self) -> list[str]: ...Comprehensive request validation interfaces for both OAuth 1.0 and OAuth 2.0 flows. Provides extensible validation framework for custom authentication logic and security policies.
class RequestValidator:
def validate_client_id(self, client_id: str, request, *args, **kwargs) -> bool: ...
def authenticate_client(self, request, *args, **kwargs) -> bool: ...
def validate_redirect_uri(self, client_id: str, redirect_uri: str, request, *args, **kwargs) -> bool: ...
def validate_scopes(self, client_id: str, scopes: list[str], client, request, *args, **kwargs) -> bool: ...
def save_authorization_code(self, client_id: str, code: dict, request, *args, **kwargs) -> None: ...
def save_token(self, token: dict, request, *args, **kwargs) -> None: ...Shared utilities for parameter handling, token generation, URI validation, and cryptographic operations. Includes request/response handling and OAuth-specific data structures.
class Request:
def __init__(
self,
uri: str,
http_method: str = "GET",
body: str | dict[str, str] | list[tuple[str, str]] | None = None,
headers: dict[str, str] | None = None,
encoding: str = "utf-8",
): ...
@property
def uri_query_params(self) -> list[tuple[str, str]]: ...
def generate_token(length: int = 30, chars: str = ...) -> str: ...
def generate_nonce() -> str: ...
def generate_timestamp() -> str: ...
def safe_string_equals(a: str, b: str) -> bool: ...OpenID Connect identity layer implementation providing ID tokens, UserInfo endpoint, and authentication extensions to OAuth 2.0. Includes JWT token handling and claims processing.
class RequestValidator: # OpenID Connect extension
def get_id_token(self, token: dict, token_handler, request) -> str: ...
def validate_id_token(self, token: str, scopes: list[str], request) -> bool: ...
def get_userinfo_claims(self, request) -> dict | str: ...
def validate_silent_authorization(self, request) -> bool: ...
class Server:
def create_userinfo_response(
self,
uri: str,
http_method: str = "GET",
body: str | None = None,
headers: dict[str, str] | None = None,
**kwargs,
) -> tuple[dict[str, str], str, int]: ...OAuth 2.0 device authorization grant (RFC 8628) for input-constrained devices like smart TVs, game consoles, and IoT devices. Provides device and user codes for out-of-band authorization.
class DeviceClient:
def prepare_device_authorization_request(
self,
device_authorization_endpoint: str,
scope: str | list[str] | None = None,
**kwargs,
) -> tuple[str, dict[str, str], str]: ...
class DeviceAuthorizationEndpoint:
def create_device_authorization_response(
self,
uri: str,
http_method: str = "POST",
body: str | None = None,
headers: dict[str, str] | None = None,
**kwargs,
) -> tuple[dict[str, str], str, int]: ...Comprehensive exception hierarchy for OAuth 1.0, OAuth 2.0, and OpenID Connect errors. Provides specific error types for different failure scenarios with proper HTTP status codes and error responses.
class OAuth2Error(Exception):
error: str | None
status_code: int
description: str
def in_uri(self, uri: str) -> str: ...
@property
def json(self) -> str: ...
class InvalidClientError(OAuth2Error): ...
class InvalidGrantError(OAuth2Error): ...
class AccessDeniedError(OAuth2Error): ...
class InvalidScopeError(OAuth2Error): ...# Core module functions
def set_debug(debug_val: bool) -> None:
"""Set debug mode for the library."""
def get_debug() -> bool:
"""Get current debug mode status."""
# Module metadata
__author__: str
__version__: str
# HTTP method types
_HTTPMethod = Literal["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"]
# Token placement options
_TokenPlacement = Literal["auth_header", "query", "body"]
# Case-insensitive dictionary for headers
class CaseInsensitiveDict(dict[str, Any]):
def __init__(self, data: dict[str, Any]) -> None: ...
def __contains__(self, k: str) -> bool: ...
def __getitem__(self, k: str): ...
def get(self, k: str, default=None): ...
# OAuth signature method constants
SIGNATURE_HMAC_SHA1: str
SIGNATURE_RSA_SHA1: str
SIGNATURE_PLAINTEXT: str
SIGNATURE_TYPE_AUTH_HEADER: str
SIGNATURE_TYPE_QUERY: str
SIGNATURE_TYPE_BODY: str