{"id":7667,"library":"requests-auth","title":"requests-auth","description":"requests-auth provides a collection of authentication classes that extend the capabilities of the popular Python `requests` library. It simplifies the implementation of various authentication schemes like OAuth2 (Authorization Code, Client Credentials, PKCE), Okta, Microsoft Entra ID (formerly Azure Active Directory), API Key, Basic, and NTLM. The current version is 8.0.0, released on June 18, 2024, and it typically follows the release cadence of its underlying `requests` and `requests-oauthlib` dependencies, with new features and bug fixes released as needed.","status":"active","version":"8.0.0","language":"en","source_language":"en","source_url":"https://github.com/Colin-b/requests_auth","tags":["authentication","requests","oauth2","api key","bearer token","ntlm","okta","azure ad"],"install":[{"cmd":"pip install requests-auth","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Core HTTP library that requests-auth extends.","package":"requests"},{"reason":"Required for OAuth2 and OpenID Connect authentication flows.","package":"requests-oauthlib","optional":true}],"imports":[{"symbol":"OAuth2AuthorizationCode","correct":"from requests_auth import OAuth2AuthorizationCode"},{"symbol":"OAuth2ClientCredentials","correct":"from requests_auth import OAuth2ClientCredentials"},{"symbol":"ApiKeyAuth","correct":"from requests_auth import ApiKeyAuth"},{"symbol":"BearerTokenAuth","correct":"from requests_auth.authentication import BearerTokenAuth"},{"symbol":"OktaAuthorizationCode","correct":"from requests_auth import OktaAuthorizationCode"},{"symbol":"MicrosoftAuthorizationCode","correct":"from requests_auth import MicrosoftAuthorizationCode"}],"quickstart":{"code":"import requests\nimport os\nfrom requests_auth import OAuth2ClientCredentials\n\n# --- Client Credentials Flow Example ---\n# Replace with your actual client_id, client_secret, token_url, and API endpoint\nCLIENT_ID = os.environ.get('OAUTH_CLIENT_ID', 'your_client_id')\nCLIENT_SECRET = os.environ.get('OAUTH_CLIENT_SECRET', 'your_client_secret')\nTOKEN_URL = os.environ.get('OAUTH_TOKEN_URL', 'https://example.com/oauth/token')\nAPI_ENDPOINT = os.environ.get('API_ENDPOINT', 'https://api.example.com/data')\n\nif CLIENT_ID and CLIENT_SECRET and TOKEN_URL and API_ENDPOINT:\n    try:\n        # Initialize OAuth2ClientCredentials auth\n        auth = OAuth2ClientCredentials(\n            token_url=TOKEN_URL,\n            client_id=CLIENT_ID,\n            client_secret=CLIENT_SECRET\n        )\n\n        # Make an authenticated request\n        response = requests.get(API_ENDPOINT, auth=auth)\n        response.raise_for_status() # Raise an exception for HTTP errors\n        print(f\"Client Credentials API Response: {response.json()}\")\n    except requests.exceptions.HTTPError as e:\n        print(f\"Client Credentials HTTP Error: {e.response.status_code} - {e.response.text}\")\n    except Exception as e:\n        print(f\"An error occurred during Client Credentials flow: {e}\")\nelse:\n    print(\"Skipping Client Credentials example: Environment variables for client ID, secret, token URL, or API endpoint are not set.\")\n\n# --- API Key in Header Example ---\n# Replace with your actual API key and endpoint\nAPI_KEY_HEADER = os.environ.get('API_KEY_HEADER', 'your_api_key_value')\nAPI_KEY_HEADER_NAME = 'X-API-Key'\nAPI_ENDPOINT_HEADER = os.environ.get('API_ENDPOINT_HEADER', 'https://api.example.com/header-data')\n\nif API_KEY_HEADER and API_ENDPOINT_HEADER:\n    try:\n        # Initialize ApiKeyAuth for header\n        auth_header = ApiKeyAuth(\n            API_KEY_HEADER, \n            API_KEY_HEADER_NAME, \n            'header'\n        )\n\n        response_header = requests.get(API_ENDPOINT_HEADER, auth=auth_header)\n        response_header.raise_for_status()\n        print(f\"API Key (Header) API Response: {response_header.json()}\")\n    except requests.exceptions.HTTPError as e:\n        print(f\"API Key (Header) HTTP Error: {e.response.status_code} - {e.response.text}\")\n    except Exception as e:\n        print(f\"An error occurred during API Key (Header) example: {e}\")\nelse:\n    print(\"Skipping API Key (Header) example: Environment variables for API key or endpoint are not set.\")\n\n# --- Bearer Token Auth Example (using a pre-obtained token) ---\n# In a real application, this token would typically come from an OAuth2 flow.\nBEARER_TOKEN = os.environ.get('BEARER_TOKEN', 'your_bearer_token')\nAPI_ENDPOINT_BEARER = os.environ.get('API_ENDPOINT_BEARER', 'https://api.example.com/bearer-data')\n\nif BEARER_TOKEN and API_ENDPOINT_BEARER:\n    try:\n        # Initialize BearerTokenAuth\n        bearer_auth = BearerTokenAuth(BEARER_TOKEN)\n\n        response_bearer = requests.get(API_ENDPOINT_BEARER, auth=bearer_auth)\n        response_bearer.raise_for_status()\n        print(f\"Bearer Token API Response: {response_bearer.json()}\")\n    except requests.exceptions.HTTPError as e:\n        print(f\"Bearer Token HTTP Error: {e.response.status_code} - {e.response.text}\")\n    except Exception as e:\n        print(f\"An error occurred during Bearer Token example: {e}\")\nelse:\n    print(\"Skipping Bearer Token example: Environment variables for bearer token or endpoint are not set.\")","lang":"python","description":"This quickstart demonstrates how to use `requests-auth` for three common authentication patterns: OAuth2 Client Credentials flow, API Key in a header, and Bearer Token authentication. It retrieves sensitive credentials from environment variables for security. Ensure you replace placeholder URLs and environment variable names with your actual API details."},"warnings":[{"fix":"For headless environments, configure display settings or use a flow like Client Credentials that does not require user browser interaction. E.g., `OAuth2AuthorizationCode(..., display_settings=DisplaySettings(display=DisplayType.NONE))`.","message":"When using OAuth2 flows (e.g., Authorization Code), requests-auth might attempt to open a web browser for user interaction. This can be problematic in headless environments or CI/CD pipelines. Refer to the library's documentation for headless options if available (e.g., `display_settings`).","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Use the `auth` parameter with `HTTPBasicAuth` or a tuple `auth=('username', 'password')` with `requests`. For `requests-auth`, many of its classes abstract this, but be mindful when integrating. Example: `requests.get(url, auth=('username', 'password'))`.","message":"Directly passing username and password for basic authentication in a URL (e.g., `http://user:pass@example.com`) is generally not recommended as it can expose credentials in logs or browser history. While `requests` supports a tuple `auth=('user', 'pass')`, ensure sensitive information is handled securely.","severity":"gotcha","affected_versions":"All versions of requests and requests-auth relying on basic auth."},{"fix":"Always review the changelog of the underlying `requests` library when upgrading `requests-auth`. Ensure your application's Python version meets the requirements of both libraries. For example, `requests` dropped Python 3.8 support after 2.32.5.","message":"No explicit breaking changes for `requests-auth` version 8.0.0 were found in its direct changelog or release notes. However, it relies heavily on the `requests` library. Upgrades to `requests` itself (e.g., 2.31.0+ fixed a Proxy-Authorization header forwarding vulnerability, and future versions might drop older Python support) could indirectly impact applications using `requests-auth`.","severity":"breaking","affected_versions":"All versions of requests-auth implicitly dependent on requests behavior."}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure the library is installed in the active Python environment: `pip install requests-auth`.","cause":"`requests-auth` library is not installed or the Python environment where it was installed is not the one being used to run the script.","error":"ModuleNotFoundError: No module named 'requests_auth'"},{"fix":"Verify that your credentials are correct, up-to-date, and have the necessary scopes/permissions. Double-check for typos, leading/trailing spaces, or improper encoding. Consult the API documentation for correct authentication methods and required parameters.","cause":"The provided authentication credentials (API key, OAuth token, client ID/secret, username/password) are incorrect, expired, or lack the necessary permissions for the requested resource.","error":"requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: ..."},{"fix":"For Authorization Code flow, ensure the `redirect_uri` in the initial authorization request exactly matches the one used to exchange the code for a token. Verify the client ID and secret. Ensure that the authorization code hasn't been used multiple times or expired. Check server time synchronization. If using refresh tokens, ensure they are valid and not expired/revoked.","cause":"Common in OAuth2 flows when the authorization code or refresh token is invalid, expired, revoked, or does not match the redirection URI/client for which it was issued. This can also occur if the client secret is incorrect or if the server clock is out of sync.","error":"requests.exceptions.HTTPError: 400 Bad Request: {'error': 'invalid_grant', 'error_description': '...'}"}]}