A Python OAuth 1.0 library providing comprehensive authentication, signing, and client capabilities.
—
Essential OAuth 1.0 functionality providing consumer and token management, request construction, parameter normalization, and signature generation. These core components form the foundation for all OAuth authentication workflows.
OAuth consumers represent third-party applications that want to access protected resources. The Consumer class manages application credentials and provides string serialization for debugging.
class Consumer:
def __init__(self, key: str, secret: str):
"""
Initialize OAuth consumer with application credentials.
Args:
key (str): Consumer key from service provider
secret (str): Consumer secret from service provider
Raises:
ValueError: If key or secret is None
"""
def __str__(self) -> str:
"""Return URL-encoded string representation of consumer credentials."""OAuth tokens represent user authorization credentials, including both request tokens (for authorization) and access tokens (for accessing protected resources).
class Token:
def __init__(self, key: str, secret: str):
"""
Initialize OAuth token with user credentials.
Args:
key (str): Token key from OAuth flow
secret (str): Token secret from OAuth flow
Raises:
ValueError: If key or secret is None
"""
def set_callback(self, callback: str):
"""
Set callback URL for OAuth 1.0a flow.
Args:
callback (str): Callback URL for authorization
"""
def set_verifier(self, verifier: str = None):
"""
Set OAuth verifier for token exchange.
Args:
verifier (str, optional): OAuth verifier. If None, generates random verifier.
"""
def get_callback_url(self) -> str:
"""
Get callback URL with oauth_verifier parameter appended.
Returns:
str: Callback URL with verifier parameter
"""
def to_string(self) -> str:
"""
Serialize token to URL-encoded string including secret.
Returns:
str: Token serialized as query parameters
"""
@staticmethod
def from_string(s: str):
"""
Deserialize token from URL-encoded string.
Args:
s (str): URL-encoded token string
Returns:
Token: Deserialized token object
Raises:
ValueError: If string format is invalid or missing required parameters
"""
def __str__(self) -> str:
"""Return string representation of token."""The Request class manages OAuth request parameters, handles normalization, and coordinates the signing process. It extends Python's dict to provide parameter access.
class Request(dict):
def __init__(self, method: str = 'GET', url: str = None, parameters: dict = None, body: bytes = b'', is_form_encoded: bool = False):
"""
Initialize OAuth request with HTTP parameters.
Args:
method (str): HTTP method (default: 'GET')
url (str): Request URL
parameters (dict): Request parameters
body (bytes): Request body for POST requests
is_form_encoded (bool): Whether body is form-encoded
"""
def get_nonoauth_parameters(self) -> dict:
"""
Extract non-OAuth parameters from request.
Returns:
dict: Parameters not starting with 'oauth_'
"""
def to_header(self, realm: str = '') -> dict:
"""
Serialize OAuth parameters as Authorization header.
Args:
realm (str): OAuth realm parameter
Returns:
dict: Dictionary with 'Authorization' header
"""
def to_postdata(self) -> str:
"""
Serialize all parameters as POST body data.
Returns:
str: URL-encoded parameter string
"""
def to_url(self) -> str:
"""
Serialize parameters as URL query string for GET requests.
Returns:
str: Complete URL with parameters
"""
def get_parameter(self, parameter: str):
"""
Get specific parameter value.
Args:
parameter (str): Parameter name
Returns:
Parameter value
Raises:
Error: If parameter not found
"""
def get_normalized_parameters(self) -> str:
"""
Generate normalized parameter string for signature base.
Returns:
str: Normalized parameters per OAuth spec
"""
def sign_request(self, signature_method, consumer, token):
"""
Sign the request using specified signature method.
Args:
signature_method: Signature method instance
consumer: Consumer credentials
token: Token credentials (optional)
"""
@classmethod
def make_timestamp(cls) -> str:
"""
Generate OAuth timestamp (seconds since epoch).
Returns:
str: Current timestamp
"""
@classmethod
def make_nonce(cls) -> str:
"""
Generate OAuth nonce (random number).
Returns:
str: Random nonce value
"""
@classmethod
def from_request(cls, http_method: str, http_url: str, headers: dict = None, parameters: dict = None, query_string: str = None):
"""
Create Request from HTTP request components.
Args:
http_method (str): HTTP method
http_url (str): Request URL
headers (dict): HTTP headers
parameters (dict): Request parameters
query_string (str): URL query string
Returns:
Request: Request object or None if no OAuth parameters
"""
@classmethod
def from_consumer_and_token(cls, consumer, token=None, http_method: str = 'GET', http_url: str = None, parameters: dict = None, body: bytes = b'', is_form_encoded: bool = False):
"""
Create Request from consumer and token credentials.
Args:
consumer: Consumer credentials
token: Token credentials (optional)
http_method (str): HTTP method
http_url (str): Request URL
parameters (dict): Additional parameters
body (bytes): Request body
is_form_encoded (bool): Whether body is form-encoded
Returns:
Request: Configured request object
"""
@classmethod
def from_token_and_callback(cls, token, callback: str = None, http_method: str = 'GET', http_url: str = None, parameters: dict = None):
"""
Create Request from token and callback for authorization flow.
Args:
token: Token credentials
callback (str): Callback URL
http_method (str): HTTP method
http_url (str): Request URL
parameters (dict): Additional parameters
Returns:
Request: Configured request object
"""OAuth signature methods provide pluggable signing algorithms. The library includes HMAC-SHA1 (recommended) and PLAINTEXT methods.
class SignatureMethod:
"""Abstract base class for signature methods."""
def signing_base(self, request, consumer, token) -> tuple:
"""
Calculate the signature base string and signing key.
Args:
request: Request object
consumer: Consumer credentials
token: Token credentials
Returns:
tuple: (signing_key, base_string)
"""
def sign(self, request, consumer, token) -> bytes:
"""
Generate signature for the request.
Args:
request: Request object
consumer: Consumer credentials
token: Token credentials
Returns:
bytes: Generated signature
"""
def check(self, request, consumer, token, signature: str) -> bool:
"""
Verify signature against request.
Args:
request: Request object
consumer: Consumer credentials
token: Token credentials
signature (str): Signature to verify
Returns:
bool: True if signature is valid
"""
class SignatureMethod_HMAC_SHA1(SignatureMethod):
"""HMAC-SHA1 signature method (recommended)."""
name = 'HMAC-SHA1'
def signing_base(self, request, consumer, token) -> tuple:
"""Calculate HMAC-SHA1 signing base and key."""
def sign(self, request, consumer, token) -> bytes:
"""Generate HMAC-SHA1 signature."""
class SignatureMethod_PLAINTEXT(SignatureMethod):
"""PLAINTEXT signature method (less secure)."""
name = 'PLAINTEXT'
def signing_base(self, request, consumer, token) -> tuple:
"""Calculate PLAINTEXT signing base and key."""
def sign(self, request, consumer, token) -> bytes:
"""Generate PLAINTEXT signature."""Helper functions for common OAuth operations including parameter generation, string encoding, and authentication headers.
def build_authenticate_header(realm: str = '') -> dict:
"""
Build WWW-Authenticate header for 401 responses.
Args:
realm (str): OAuth realm parameter
Returns:
dict: Header dictionary with WWW-Authenticate
"""
def build_xoauth_string(url: str, consumer, token=None) -> str:
"""
Build XOAUTH string for SMTP/IMAP authentication.
Args:
url (str): Service URL
consumer: Consumer credentials
token: Token credentials (optional)
Returns:
str: XOAUTH authentication string
"""
def escape(s: str) -> str:
"""
URL escape string including forward slashes.
Args:
s (str): String to escape
Returns:
str: URL-escaped string
"""
def generate_timestamp() -> int:
"""
Generate OAuth timestamp (seconds since epoch).
Returns:
int: Current timestamp
"""
def generate_nonce(length: int = 8) -> str:
"""
Generate pseudorandom nonce.
Args:
length (int): Nonce length in digits
Returns:
str: Random numeric string
"""
def generate_verifier(length: int = 8) -> str:
"""
Generate pseudorandom verifier for OAuth 1.0a.
Args:
length (int): Verifier length in digits
Returns:
str: Random numeric string
"""
def to_unicode(s) -> str:
"""
Convert to unicode with proper error handling.
Args:
s: String or bytes to convert
Returns:
str: Unicode string
Raises:
TypeError: If input is not string or bytes, or contains invalid UTF-8
"""
def to_utf8(s) -> bytes:
"""
Convert unicode string to UTF-8 bytes.
Args:
s: String to convert
Returns:
bytes: UTF-8 encoded bytes
"""
def to_unicode_if_string(s):
"""
Convert to unicode only if input is a string type.
Args:
s: Value to potentially convert
Returns:
Unicode string if input was string, otherwise unchanged
"""
def to_utf8_if_string(s):
"""
Convert to UTF-8 bytes only if input is a string type.
Args:
s: Value to potentially convert
Returns:
UTF-8 bytes if input was string, otherwise unchanged
"""
def to_unicode_optional_iterator(x):
"""
Convert string or iterable of strings to unicode.
Args:
x: String or iterable to convert
Returns:
Unicode string or list of unicode strings
Raises:
TypeError: If contains invalid UTF-8
"""
def to_utf8_optional_iterator(x):
"""
Convert string or iterable of strings to UTF-8 bytes.
Args:
x: String or iterable to convert
Returns:
UTF-8 bytes or list of UTF-8 byte strings
"""import oauth2
# Create credentials
consumer = oauth2.Consumer('consumer_key', 'consumer_secret')
token = oauth2.Token('token_key', 'token_secret')
# Create and sign request
request = oauth2.Request.from_consumer_and_token(
consumer=consumer,
token=token,
http_method='GET',
http_url='https://api.example.com/data'
)
signature_method = oauth2.SignatureMethod_HMAC_SHA1()
request.sign_request(signature_method, consumer, token)
# Get authorization header
headers = request.to_header()
print(headers['Authorization'])import oauth2
# Create token
token = oauth2.Token('token_key', 'token_secret')
token.set_callback('https://myapp.com/callback')
token.set_verifier('verification_code')
# Serialize for storage
token_string = token.to_string()
# Deserialize from storage
restored_token = oauth2.Token.from_string(token_string)import oauth2
# Handle different string types for OAuth parameters
raw_data = b'some bytes data'
unicode_data = oauth2.to_unicode(raw_data) # Convert to unicode
utf8_data = oauth2.to_utf8(unicode_data) # Convert back to UTF-8
# Conditional conversion
mixed_data = ['string1', b'bytes2', 'string3']
converted = [oauth2.to_unicode_if_string(item) for item in mixed_data]
# Handle iterables
parameter_list = ['param1', 'param2', 'param3']
unicode_params = oauth2.to_unicode_optional_iterator(parameter_list)Install with Tessl CLI
npx tessl i tessl/pypi-oauth2