The ultimate Python library in building OAuth and OpenID Connect servers and clients.
npx @tessl/cli install tessl/pypi-authlib@1.6.0The ultimate Python library in building OAuth and OpenID Connect servers and clients. Authlib provides comprehensive implementations of OAuth 1.0, OAuth 2.0, and OpenID Connect protocols, along with JSON Web Token (JWT) and JSON Object Signing and Encryption (JOSE) standards. It offers spec-compliant implementations covering the entire OAuth ecosystem with built-in support for popular Python web frameworks including Flask, Django, Starlette, and FastAPI.
pip install authlibimport authlib
from authlib import __version__Protocol-specific imports:
# JOSE (JWT, JWS, JWE, JWK)
from authlib.jose import JsonWebSignature, JsonWebEncryption, JsonWebKey, JsonWebToken, jwt
# OAuth 1.0
from authlib.oauth1 import OAuth1Request, AuthorizationServer, ResourceProtector, OAuth1Client
# OAuth 2.0
from authlib.oauth2 import OAuth2Client, AuthorizationServer, ResourceProtector, OAuth2Request
# OpenID Connect
from authlib.oidc.core import IDToken, UserInfo, UserInfoEndpointFramework integrations:
# Flask
from authlib.integrations.flask_client import OAuth
from authlib.integrations.flask_oauth2 import AuthorizationServer
# Django
from authlib.integrations.django_oauth2 import AuthorizationServer
# Requests/HTTPX
from authlib.integrations.requests_client import OAuth1Session, OAuth2Session
from authlib.integrations.httpx_client import OAuth1Client, OAuth2Clientfrom authlib.jose import JsonWebToken, jwt
# Create a JWT token
header = {'alg': 'HS256'}
payload = {'user_id': 123, 'username': 'alice'}
secret = 'your-secret-key'
token = jwt.encode(header, payload, secret)
print(token) # JWT token string
# Decode and validate JWT token
data = jwt.decode(token, secret)
print(data) # {'user_id': 123, 'username': 'alice'}from authlib.integrations.requests_client import OAuth2Session
# Create OAuth 2.0 client
client = OAuth2Session(
client_id='your-client-id',
client_secret='your-client-secret',
redirect_uri='https://your-app.com/callback'
)
# Authorization URL
authorization_url, state = client.create_authorization_url(
'https://provider.com/authorize',
scope='read write'
)
# Exchange authorization code for token
token = client.fetch_token(
'https://provider.com/token',
authorization_response='https://your-app.com/callback?code=...'
)
# Make authenticated requests
response = client.get('https://api.provider.com/user')from authlib.oidc.core import IDToken
from authlib.jose import JsonWebToken
# Validate ID Token
id_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...'
jwt = JsonWebToken(['RS256'])
# Claims validation
claims = jwt.decode(id_token, public_key)
id_token_claims = IDToken(claims)
id_token_claims.validate()Authlib is organized into several key modules:
The library provides both high-level framework integrations and low-level protocol implementations, allowing developers to choose the appropriate abstraction level for their needs.
Complete implementation of JOSE standards including JWT (JSON Web Tokens), JWS (JSON Web Signature), JWE (JSON Web Encryption), and JWK (JSON Web Keys). Supports all standard algorithms and provides both high-level JWT operations and low-level JOSE primitives.
class JsonWebToken:
def encode(self, header: dict, payload: dict, key: str) -> str: ...
def decode(self, data: str, key: str) -> dict: ...
class JsonWebSignature:
def serialize_compact(self, protected: dict, payload: bytes, key: str) -> str: ...
def deserialize_compact(self, data: str, key: str) -> dict: ...
class JsonWebKey:
def import_key(self, key: str) -> Key: ...
def export_key(self) -> str: ...Full OAuth 1.0 implementation supporting all signature methods (HMAC-SHA1, RSA-SHA1, PLAINTEXT) and signature types (header, query, body). Provides both client and server implementations with support for temporary credentials and token credentials.
class OAuth1Client:
def __init__(self, client_key: str, client_secret: str = None) -> None: ...
def fetch_request_token(self, uri: str, realm: str = None) -> dict: ...
def fetch_access_token(self, uri: str, verifier: str = None) -> dict: ...
class AuthorizationServer:
def __init__(self, query_client: callable, query_token: callable) -> None: ...
def validate_request(self, uri: str, http_method: str, body: str, headers: dict) -> None: ...Comprehensive OAuth 2.0 implementation supporting all standard grant types: authorization code, implicit, resource owner password credentials, client credentials, and refresh token. Includes support for PKCE, device flow, and bearer tokens.
class OAuth2Client:
def __init__(self, client_id: str, client_secret: str = None) -> None: ...
def create_authorization_url(self, authorization_endpoint: str, **kwargs) -> tuple: ...
def fetch_token(self, token_endpoint: str, **kwargs) -> dict: ...
class AuthorizationServer:
def __init__(self, query_client: callable, save_token: callable) -> None: ...
def validate_consent_request(self, request: OAuth2Request) -> None: ...
def create_authorization_response(self, request: OAuth2Request, grant_user: callable) -> HttpResponse: ...OpenID Connect implementation built on OAuth 2.0, providing ID tokens, UserInfo endpoint, and discovery mechanisms. Supports all OpenID Connect flows: authorization code, implicit, and hybrid.
class IDToken:
def __init__(self, claims: dict) -> None: ...
def validate(self, now: int = None) -> None: ...
class UserInfo:
def __init__(self, sub: str, **claims) -> None: ...
def __call__(self, claims: list = None) -> dict: ...
class UserInfoEndpoint:
def create_userinfo_response(self, request: OAuth2Request) -> HttpResponse: ...Complete Flask integration providing OAuth client registry and OAuth 2.0 server implementations. Supports automatic token management, session integration, and Flask-specific request/response handling.
class OAuth:
def __init__(self, app: Flask = None) -> None: ...
def register(self, name: str, **kwargs) -> FlaskOAuth2App: ...
class AuthorizationServer:
def __init__(self, app: Flask = None) -> None: ...
def init_app(self, app: Flask, query_client: callable, save_token: callable) -> None: ...Django-specific OAuth 2.0 server implementation with Django model integration, middleware support, and Django-specific request/response handling.
class AuthorizationServer:
def __init__(self, query_client: callable, save_token: callable) -> None: ...
def create_token_response(self, request: HttpRequest) -> HttpResponse: ...
class ResourceProtector:
def __init__(self, require_oauth: callable = None) -> None: ...
def acquire_token(self, request: HttpRequest, scope: str = None) -> OAuth2Token: ...Seamless integration with popular HTTP clients including Requests and HTTPX for both synchronous and asynchronous OAuth operations. Provides automatic token management and request signing.
# Requests integration
class OAuth1Session:
def __init__(self, client_key: str, client_secret: str = None) -> None: ...
class OAuth2Session:
def __init__(self, client_id: str, client_secret: str = None) -> None: ...
# HTTPX integration
class OAuth1Client:
def __init__(self, client_key: str, client_secret: str = None) -> None: ...
class OAuth2Client:
def __init__(self, client_id: str, client_secret: str = None) -> None: ...Shared utilities for encoding, security operations, URL handling, and error management used throughout the library. Provides consistent behavior and security best practices.
def generate_token(length: int = 30, chars: str = None) -> str: ...
def is_secure_transport(uri: str) -> bool: ...
def url_encode(params: dict) -> str: ...
def url_decode(query: str) -> dict: ...Authlib provides comprehensive error handling with specific exception classes for different protocols and scenarios:
class AuthlibBaseError(Exception): ...
class OAuth2Error(AuthlibBaseError): ...
class JoseError(AuthlibBaseError): ...
class InvalidTokenError(OAuth2Error): ...
class ExpiredTokenError(JoseError): ...All errors include detailed messages and, where applicable, HTTP status codes for proper error responses in server implementations.