Mastercard OAuth1 Signer
The Mastercard OAuth1 Signer is a Python library that simplifies the process of generating OAuth 1.0a signatures required for authenticating requests to Mastercard APIs. It handles the complexities of OAuth 1.0a, including nonce generation, timestamping, and RSA-SHA256 signature creation. The current version is 1.9.2, with a release cadence focused on security updates, dependency bumps, and bug fixes.
Common errors
-
ModuleNotFoundError: No module named 'mastercard.oauth1.signer'
cause The `mastercard-oauth1-signer` package is not installed in the current Python environment or the import path is incorrect.fixInstall the library: `pip install mastercard-oauth1-signer`. Verify your import statement: `from mastercard.oauth1.signer import Auth`. -
mastercard.oauth1.signer.utils.MastercardOAuth1SignerException: Failed to sign request: [Specific error message related to key/auth]
cause This generic exception usually indicates an issue with the provided credentials (consumer key, private key path, password, or alias) or an internal error during the signing process.fixCarefully review all parameters passed to the `Auth` constructor: `consumer_key`, `private_key_path`, `private_key_password`, and `private_key_alias`. Ensure the `.p12` file exists, is accessible, and not corrupted. Check for typos and verify against your Mastercard Developer credentials. -
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: ...
cause The API endpoint rejected the signed request, most commonly due to an invalid or mismatched OAuth signature. This could stem from incorrect credentials, an improperly formatted request URL, or a mismatch in API environment (e.g., sandbox vs. production).fixConfirm your `consumer_key`, `private_key_path`, `key_alias`, and `key_password` are correct. Verify that the `BASE_URL` matches the intended API environment (sandbox or production) and that the endpoint path is accurate. Ensure any request parameters or body content are consistent with the API documentation for signature generation.
Warnings
- breaking The `oauth_signature` was not encoded correctly in versions 1.2.0 and 1.3.0, leading to authentication failures for affected API calls. This was resolved in version 1.4.0.
- gotcha A critical vulnerability (CVE-2023-49082) was found in Cryptography library version 41.0.0. The `mastercard-oauth1-signer` library explicitly updated its `cryptography` dependency to address this, but if your environment has an older version installed, it could pose a risk.
- gotcha Dependency on `pyOpenSSL` has seen several version bumps and adjustments across releases (e.g., 1.6.0, 1.6.1, 1.7.0, 1.9.0). Users might encounter dependency conflicts or `ImportError` issues if their environment has specific `pyOpenSSL` versions that clash with the library's requirements.
- gotcha When loading the private key from a `.p12` file, ensure the `private_key_alias` and `private_key_password` are correct. Incorrect values will lead to `MastercardOAuth1SignerException` during `Auth` object initialization.
Install
-
pip install mastercard-oauth1-signer
Imports
- Auth
from mastercard.oauth1.signer import Auth
Quickstart
import requests
import os
from mastercard.oauth1.signer import Auth
# --- Environment variables or placeholder values ---
# Replace with your actual credentials or set as environment variables
CONSUMER_KEY = os.environ.get('MASTERCARD_CONSUMER_KEY', 'YOUR_CONSUMER_KEY')
PRIVATE_KEY_PATH = os.environ.get('MASTERCARD_PRIVATE_KEY_PATH', 'path/to/your/key.p12')
KEY_ALIAS = os.environ.get('MASTERCARD_KEY_ALIAS', 'keyalias') # Alias used when creating the .p12 file
KEY_PASSWORD = os.environ.get('MASTERCARD_KEY_PASSWORD', 'keypassword')
BASE_URL = os.environ.get('MASTERCARD_BASE_URL', 'https://sandbox.api.mastercard.com') # Or 'https://api.mastercard.com'
# --- Load private key and create Auth object ---
try:
# The Auth constructor handles loading the private key from the .p12 file
oauth_auth = Auth(
consumer_key=CONSUMER_KEY,
private_key_path=PRIVATE_KEY_PATH,
private_key_password=KEY_PASSWORD,
private_key_alias=KEY_ALIAS
)
except Exception as e:
print(f"Error initializing Auth: {e}")
print("Please ensure your private key path, password, and alias are correct.")
exit(1)
# --- Example API call (replace with your actual endpoint) ---
# This example assumes an endpoint that returns some data, like a health check or a simple resource.
# The actual endpoint will vary based on the Mastercard API you are using.
api_endpoint = f"{BASE_URL}/some/api/resource"
headers = {'Accept': 'application/json'}
try:
response = requests.get(api_endpoint, auth=oauth_auth, headers=headers)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
print(f"Successfully called {api_endpoint}")
print(f"Status Code: {response.status_code}")
print("Response Body:")
print(response.json()) # Assuming JSON response
except requests.exceptions.RequestException as e:
print(f"API call failed: {e}")
if hasattr(e, 'response') and e.response is not None:
print(f"Response Status: {e.response.status_code}")
print(f"Response Body: {e.response.text}")
except Exception as e:
print(f"An unexpected error occurred: {e}")