or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

common-utilities.mddevice-flow.mderror-handling.mdindex.mdoauth1.mdoauth2-clients.mdoauth2-servers.mdopenid-connect.mdrequest-validation.mdtoken-management.md
tile.json

tessl/pypi-oauthlib

A comprehensive Python library for implementing OAuth 1.0 and OAuth 2.0 authentication protocols

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/oauthlib@3.3.x

To install, run

npx @tessl/cli install tessl/pypi-oauthlib@3.3.0

index.mddocs/

Types OAuthlib

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

Package Information

  • Package Name: types-oauthlib
  • Language: Python
  • Installation: pip install types-oauthlib
  • Requires: oauthlib library (pip install oauthlib)

Core Imports

import oauthlib
from oauthlib import oauth1, oauth2, openid, common

# Debug functions
from oauthlib import set_debug, get_debug

OAuth 1.0 specific imports:

from oauthlib.oauth1 import Client, RequestValidator
from oauthlib.oauth1 import AccessTokenEndpoint, AuthorizationEndpoint, RequestTokenEndpoint

OAuth 2.0 specific imports:

from oauthlib.oauth2 import WebApplicationClient, BackendApplicationClient
from oauthlib.oauth2 import AuthorizationEndpoint, TokenEndpoint, ResourceEndpoint
from oauthlib.oauth2 import RequestValidator, BearerToken

OpenID Connect specific imports:

from oauthlib.openid import RequestValidator, Server, UserInfoEndpoint

Basic Usage

OAuth 2.0 Client Example

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

OAuth 2.0 Server Example

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

Architecture

The oauthlib type stubs are organized into several key modules that mirror the OAuth specification hierarchy:

  • Common Module: Shared utilities, request handling, and base types used across all OAuth implementations
  • OAuth 1.0 Module: Complete RFC 5849 implementation with clients, endpoints, signature methods, and validation
  • OAuth 2.0 Module: Complete RFC 6749 implementation with multiple client types, server endpoints, grant types, and token handling
  • Device Flow Extension: RFC 8628 device authorization grant for input-constrained devices
  • OpenID Connect Module: OpenID Connect extension providing identity layer on top of OAuth 2.0

This modular architecture enables developers to use specific OAuth flows while maintaining type safety and IDE support throughout the authentication process.

Capabilities

OAuth 1.0 Implementation

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

OAuth 1.0

OAuth 2.0 Clients

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

OAuth 2.0 Clients

OAuth 2.0 Servers

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

OAuth 2.0 Servers

Token Management

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

Token Management

Request Validation

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

Request Validation

Common Utilities

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

Common Utilities

OpenID Connect

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

OpenID Connect

Device Flow

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

Device Flow

Error Handling

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

Error Handling

Types

# 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