CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-httplib2

A comprehensive HTTP client library that supports many features left out of other HTTP libraries.

Pending
Overview
Eval results
Files

authentication.mddocs/

Authentication

Multiple authentication methods including Basic, Digest, WSSE, HMAC Digest, and Google Login authentication. Authentication is handled automatically once credentials are configured, with httplib2 selecting the appropriate method based on server challenges.

Capabilities

Authentication Base Class

Base class for all authentication implementations providing the common interface for credential management and request/response processing.

class Authentication:
    """Base authentication class for all auth methods."""
    
    def __init__(self, credentials, host, request_uri, headers, response, content, http):
        """
        Initialize authentication handler.
        
        Args:
            credentials (tuple): Username/password credentials
            host (str): Target hostname
            request_uri (str): Full request URI
            headers (dict): Request headers
            response: HTTP response object
            content: Response content
            http: Http client instance
        """
    
    def request(self, method, request_uri, headers, content):
        """
        Modify request headers to add appropriate authorization.
        Override in subclasses for specific auth methods.
        
        Args:
            method (str): HTTP method
            request_uri (str): Full request URI
            headers (dict): Request headers to modify
            content: Request body content
        """
    
    def response(self, response, content):
        """
        Process authentication response for nonce updates, etc.
        Override in subclasses if needed.
        
        Args:
            response: HTTP response object
            content: Response content
            
        Returns:
            bool: True if request should be retried
        """

Basic Authentication

HTTP Basic authentication using base64-encoded username:password credentials.

class BasicAuthentication(Authentication):
    """HTTP Basic authentication implementation."""
    
    def request(self, method, request_uri, headers, content):
        """Add Basic Authorization header to request."""

Digest Authentication

HTTP Digest authentication with MD5 hashing and nonce-based challenge-response.

class DigestAuthentication(Authentication):
    """HTTP Digest authentication implementation."""
    
    def request(self, method, request_uri, headers, content, cnonce=None):
        """
        Add Digest Authorization header to request.
        
        Args:
            method (str): HTTP method
            request_uri (str): Request URI
            headers (dict): Request headers
            content: Request body
            cnonce (str): Client nonce (auto-generated if None)
        """
    
    def response(self, response, content):
        """Process digest auth response and update nonce if stale."""

WSSE Authentication

Web Services Security (WSSE) authentication using username tokens with password digests.

class WsseAuthentication(Authentication):
    """WSSE (Web Services Security) authentication implementation."""
    
    def request(self, method, request_uri, headers, content):
        """Add WSSE Authorization header with username token."""

HMAC Digest Authentication

HMAC-based digest authentication providing enhanced security over standard digest auth.

class HmacDigestAuthentication(Authentication):
    """HMAC Digest authentication implementation."""
    
    def request(self, method, request_uri, headers, content):
        """Add HMAC Digest Authorization header."""
    
    def response(self, response, content):
        """Process HMAC digest response for integrity/staleness."""

Google Login Authentication

Google Login authentication for accessing Google APIs and services.

class GoogleLoginAuthentication(Authentication):
    """Google Login authentication implementation."""
    
    def request(self, method, request_uri, headers, content):
        """Add GoogleLogin Authorization header."""

Credential Management

Classes for managing authentication credentials and client certificates.

class Credentials:
    """Container for username/password credentials."""
    
    def __init__(self):
        """Initialize empty credentials container."""
    
    def add(self, name, password, domain=""):
        """
        Add credentials for a domain.
        
        Args:
            name (str): Username
            password (str): Password
            domain (str): Domain/realm (empty for all domains)
        """
    
    def clear(self):
        """Remove all stored credentials."""
    
    def iter(self, domain):
        """
        Iterate over credentials for domain.
        
        Args:
            domain (str): Target domain
            
        Yields:
            tuple: (username, password) pairs
        """

class KeyCerts(Credentials):
    """Container for SSL client certificates."""
    
    def add(self, key, cert, domain, password):
        """
        Add client certificate for domain.
        
        Args:
            key (str): Path to private key file
            cert (str): Path to certificate file  
            domain (str): Domain for certificate
            password (str): Private key password
        """
    
    def iter(self, domain):
        """
        Iterate over certificates for domain.
        
        Args:
            domain (str): Target domain
            
        Yields:
            tuple: (key, cert, password) tuples
        """

Usage Examples

Basic Authentication

import httplib2

h = httplib2.Http()

# Add credentials for specific domain
h.add_credentials('username', 'password', 'api.example.com')

# Request will automatically use Basic auth if challenged
(resp, content) = h.request("https://api.example.com/protected")

if resp.status == 200:
    print("Authentication successful")

Multiple Credentials

import httplib2

h = httplib2.Http()

# Add credentials for different domains
h.add_credentials('user1', 'pass1', 'api1.example.com')
h.add_credentials('user2', 'pass2', 'api2.example.com')

# Add wildcard credentials (applied to any domain)
h.add_credentials('defaultuser', 'defaultpass', '')

# httplib2 will select appropriate credentials based on hostname
(resp1, content1) = h.request("https://api1.example.com/data")
(resp2, content2) = h.request("https://api2.example.com/data")

Client Certificate Authentication

import httplib2

h = httplib2.Http()

# Add client certificate for mutual TLS
h.add_certificate(
    key='/path/to/client.key',
    cert='/path/to/client.crt', 
    domain='secure.example.com',
    password='keypassword'  # If private key is encrypted
)

# Request will use client certificate for SSL/TLS handshake
(resp, content) = h.request("https://secure.example.com/api")

Mixed Authentication

import httplib2

h = httplib2.Http()

# Add both credentials and certificates
h.add_credentials('apiuser', 'apipass', 'api.example.com')
h.add_certificate('/path/to/client.key', '/path/to/client.crt', 
                  'secure.example.com')

# Different authentication methods used based on server requirements
(resp1, content1) = h.request("https://api.example.com/data")      # HTTP auth
(resp2, content2) = h.request("https://secure.example.com/data")   # Client cert

Clearing Credentials

import httplib2

h = httplib2.Http()
h.add_credentials('user', 'pass')

# Make authenticated requests...
(resp, content) = h.request("https://api.example.com/data")

# Clear all credentials for security
h.clear_credentials()

# Subsequent requests won't include authentication
(resp, content) = h.request("https://api.example.com/public")

Authentication Flow

  1. Initial Request: Client makes request without authentication
  2. Challenge: Server responds with 401 and WWW-Authenticate header
  3. Credential Selection: httplib2 selects appropriate credentials based on:
    • Domain matching (exact match or wildcard)
    • Authentication method supported (Basic, Digest, etc.)
  4. Authentication: Client retries request with appropriate Authorization header
  5. Automatic Handling: Future requests to same domain automatically include auth

Supported Authentication Methods

HTTP Basic

  • Simple username:password encoding
  • Base64 encoded credentials
  • Suitable for HTTPS connections
  • Widely supported

HTTP Digest

  • Challenge-response mechanism
  • MD5 hashing with nonces
  • More secure than Basic auth
  • Protects against replay attacks

WSSE (Web Services Security)

  • Username token with password digest
  • Timestamp-based nonce generation
  • Used in web services
  • SOAP/XML-based authentication

HMAC Digest

  • Enhanced digest authentication
  • HMAC-based message authentication
  • Stronger cryptographic security
  • Less common but more secure

Google Login

  • Google-specific authentication
  • OAuth-style token authentication
  • For Google APIs and services
  • Requires Google account credentials

Security Considerations

  • HTTPS Required: Always use HTTPS for Basic authentication
  • Credential Storage: Credentials stored in memory only
  • Domain Isolation: Credentials only sent to matching domains
  • Automatic Cleanup: Use clear_credentials() when done
  • Certificate Security: Protect private key files and passwords

Install with Tessl CLI

npx tessl i tessl/pypi-httplib2

docs

authentication.md

caching.md

error-handling.md

http-client.md

index.md

proxy-support.md

response-handling.md

utilities.md

tile.json