HTTP NTLM authentication for HTTPX
httpx-ntlm is a Python package that provides NTLM (NT LAN Manager) authentication support for the HTTPX asynchronous HTTP client library. As of version 1.4.0, it allows users to authenticate against NTLM-protected resources, adapting functionality from the requests-ntlm library. It maintains an active status with infrequent but relevant updates.
Common errors
-
httpx.HTTPStatusError: Client Error: 401 Unauthorized for url: http://ntlm_protected_site.com
cause The provided NTLM username or password is incorrect, or the username format (e.g., 'domain\username') is not matching the server's expectation.fixVerify credentials, including the domain part, and ensure they are correct. Double-check for typos or incorrect domain separators. -
ModuleNotFoundError: No module named 'httpx_ntlm'
cause The `httpx-ntlm` library has not been installed in the current Python environment.fixInstall the package using pip: `pip install httpx-ntlm`. -
AttributeError: module 'httpx_ntlm' has no attribute 'HttpNtlmAuth'
cause There is a typo in the class name or an incorrect import. The main authentication class is `HttpNtlmAuth`.fixCorrect the import statement to `from httpx_ntlm import HttpNtlmAuth` and ensure the class name `HttpNtlmAuth` is used correctly.
Warnings
- breaking httpx-ntlm version 1.4.0 introduced a minimum dependency on httpx version 0.24. If you are using an older version of httpx, you will encounter dependency resolution errors or runtime issues.
- gotcha NTLM authentication is connection-based. For optimal performance and to avoid repeated authentication handshakes, it is highly recommended to use `HttpNtlmAuth` with an `httpx.Client` instance rather than passing `auth` to individual `httpx.get()` or `httpx.post()` calls.
- deprecated NTLM is an old and less secure authentication protocol. Microsoft has announced plans to disable NTLM by default in future Windows versions, making it an eventual target for deprecation across many systems. While `httpx-ntlm` functions correctly, consider migrating to more modern and secure authentication methods like Kerberos if available in your environment.
Install
-
pip install httpx-ntlm
Imports
- HttpNtlmAuth
from httpx_ntlm import HttpNtlmAuth
Quickstart
import httpx
from httpx_ntlm import HttpNtlmAuth
import os
# Using direct request (less efficient for multiple requests)
response = httpx.get(
"http://ntlm_protected_site.com",
auth=HttpNtlmAuth(os.environ.get('NTLM_USERNAME', 'domain\\username'), os.environ.get('NTLM_PASSWORD', 'password'))
)
print(f"Direct request status: {response.status_code}")
# Using httpx.Client for connection pooling (recommended for multiple requests)
with httpx.Client(
auth=HttpNtlmAuth(os.environ.get('NTLM_USERNAME', 'domain\\username'), os.environ.get('NTLM_PASSWORD', 'password'))
) as client:
response = client.get('http://ntlm_protected_site.com/resource')
print(f"Client request status: {response.status_code}")