Ivan Chavez
Ivan Chavez

Reputation: 1

407 Proxy Authentication Required error in Python despite correct proxy setup

I’m working in a corporate environment where I need to connect to an external server through a proxy using Python. The proxy requires NTLM authentication, and I've been running into a persistent 407 (Proxy Authentication Required) error, even though I’ve configured my code to include credentials. I’ve successfully connected using similar settings in C#, but Python is proving more challenging.

The code returns a 407 Proxy Authentication Required error, indicating that my credentials are not being accepted by the proxy. When I replicate the request in C#, using similar credentials and settings, I successfully authenticate through the proxy without issues.

Error: HTTPSConnectionPool(host='target-host.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Unable to connect to proxy', OSError('Tunnel connection failed: 407 Proxy Authentication Required')))

The proxy works fine when making curl requests from the command line using the following command: curl -v --proxy-negotiate -x http://proxy.com:port https://target-host.com/

Does anyone know why requests might be failing here when curl works fine? Is there a specific approach in Python for handling NTLM/Negotiate authentication through a proxy that I might be missing?

What I’ve Tried:

  1. Setting up requests_ntlm to handle NTLM auth through the proxy.
  2. Specifying HTTP_PROXY and HTTPS_PROXY environment variables to match corporate standards.
  3. Using requests-kerberos, requests-negotiate-sspi and requests-ntlm with no success and same error.
  4. Authenticating with requests as follows:
    import requests
    from requests.auth import HTTPBasicAuth

    url = "https://target-host.com/"

    return_obj = "-"
    
    proxies = {
        "http": "http://proxy.com:port", 
        "https": "http://proxy.com:port" 
    }
   
    
    auth = HTTPBasicAuth('domain\\username', 'password')
    try:
        response = requests.get(url, proxies=proxies, auth=auth)
        return_obj = response.text


        print(f"Status Code: {response.status_code}")
        print(f"Response Body: {response.text}")
    except requests.exceptions.RequestException as e:
        # Handle any exceptions (e.g., network issues, timeouts)
        print(f"An error occurred: {e}")
    return return_obj

System and Package Details: Python 3.9.13 requests-kerberos==0.15.0 requests-negotiate-sspi==0.5.2 requests_ntlm==1.3.0 OS: Windows 11

Upvotes: 0

Views: 219

Answers (0)

Related Questions