or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

common-utilities.mddjango-integration.mdflask-integration.mdhttp-clients.mdindex.mdjose.mdoauth1.mdoauth2.mdoidc.md
tile.json

tessl/pypi-authlib

The ultimate Python library in building OAuth and OpenID Connect servers and clients.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/authlib@1.6.x

To install, run

npx @tessl/cli install tessl/pypi-authlib@1.6.0

index.mddocs/

Authlib

The 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.

Package Information

  • Package Name: Authlib
  • Language: Python
  • Installation: pip install authlib
  • License: BSD-3-Clause
  • Homepage: https://authlib.org/
  • Documentation: https://docs.authlib.org/

Core Imports

import 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, UserInfoEndpoint

Framework 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, OAuth2Client

Basic Usage

JWT Operations

from 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'}

OAuth 2.0 Client

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')

OpenID Connect

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()

Architecture

Authlib is organized into several key modules:

  • jose: JSON Object Signing and Encryption (JOSE) implementations including JWT, JWS, JWE, and JWK
  • oauth1: OAuth 1.0 protocol implementation for both clients and servers
  • oauth2: OAuth 2.0 protocol implementation with support for all standard grant types
  • oidc: OpenID Connect layer built on top of OAuth 2.0
  • integrations: Framework-specific implementations for Flask, Django, Starlette, Requests, and HTTPX
  • common: Shared utilities for encoding, security, URL handling, and error management

The library provides both high-level framework integrations and low-level protocol implementations, allowing developers to choose the appropriate abstraction level for their needs.

Capabilities

JOSE (JSON Object Signing and Encryption)

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: ...

JOSE Implementation

OAuth 1.0 Protocol

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: ...

OAuth 1.0 Implementation

OAuth 2.0 Protocol

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: ...

OAuth 2.0 Implementation

OpenID Connect

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: ...

OpenID Connect Implementation

Flask Integration

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: ...

Flask Integration

Django Integration

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: ...

Django Integration

HTTP Client Integrations

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: ...

HTTP Client Integrations

Common Utilities

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: ...

Common Utilities

Error Handling

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.