requests-ntlm: NTLM Authentication for Requests
This package enables HTTP NTLM authentication for the popular Python requests library. It provides a simple `HttpNtlmAuth` class that integrates seamlessly with `requests.Session` for handling NTLM challenges. The current version is 1.3.0, and it follows an active maintenance cadence with releases addressing compatibility, security, and minor enhancements.
Warnings
- breaking Starting with v1.3.0, `requests-ntlm` will now explicitly throw an exception (`requests.exceptions.HTTPError` or similar, potentially wrapped) in case of access denied, rather than silently returning an unsuccessful response or handling it internally. This changes error handling behavior.
- gotcha Versions prior to `v1.3.0` might suffer from issues related to type annotations or compatibility with certain `pyspnego` versions, potentially leading to runtime errors or incorrect behavior.
- gotcha The library underwent a significant internal migration to use `PySPNEGO` as its underlying NTLM provider in `v1.2.0`. While the public API (`HttpNtlmAuth`) was designed to remain compatible, subtle behavioral changes or new dependency requirements (`pyspnego`) might affect existing integrations, especially in edge cases or complex NTLM environments.
- gotcha Versions of `requests-ntlm` prior to `v1.1.0` had issues correctly parsing User Principal Names (UPN) when passed as usernames (e.g., `user@domain.com`). This could lead to authentication failures.
- breaking `requests-ntlm` explicitly requires Python 3.8 or newer. Attempts to install or run it on older Python versions will fail.
Install
-
pip install requests-ntlm
Imports
- HttpNtlmAuth
from requests_ntlm import HttpNtlmAuth
Quickstart
import requests
from requests_ntlm import HttpNtlmAuth
import os
# Replace with your NTLM-protected URL
url = os.environ.get('NTLM_TEST_URL', 'http://ntlm-protected-server.local/api/')
# Replace with your NTLM credentials
username = os.environ.get('NTLM_USERNAME', 'DOMAIN\\user')
password = os.environ.get('NTLM_PASSWORD', 'your_password')
try:
session = requests.Session()
session.auth = HttpNtlmAuth(username, password)
response = session.get(url)
response.raise_for_status() # Raise an exception for bad status codes
print(f"Successfully authenticated to {url}")
print("Response content (first 200 chars):\n", response.text[:200])
except requests.exceptions.RequestException as e:
print(f"Error connecting or authenticating: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")