liorda
liorda

Reputation: 1572

Automatic NTLM with python on Windows

How can I use automatic NTLM authentication from python on Windows?

I want to be able to access the TFS REST API from windows without hardcoding my password, the same as I do from the web browser (firefox's network.automatic-ntlm-auth.trusted-uris, for example).

Upvotes: 4

Views: 18356

Answers (4)

I found solution here https://github.com/mullender/python-ntlm/issues/21

pip install requests
pip install requests_negotiate_sspi
import requests
from requests_negotiate_sspi import HttpNegotiateAuth

GetUrl = "http://servername/api/controller/Methodname" # Here you need to set your get Web api url
response = requests.get(GetUrl, auth=HttpNegotiateAuth())
print("Get Request Outpot:")
print("--------------------")
print(response.content)

for request by https:

import requests
from requests_negotiate_sspi import HttpNegotiateAuth

import urllib3
urllib3.disable_warnings()

GetUrl = "https://servername/api/controller/Methodname" # Here you need to set your get Web api url
response = requests.get(GetUrl, auth=HttpNegotiateAuth(), verify=False)
print("Get Request Outpot:")
print("--------------------")
print(response.content)

Upvotes: 1

schlamar
schlamar

Reputation: 9511

You can do that with https://github.com/requests/requests-kerberos. Under the hood it's using https://github.com/mongodb-labs/winkerberos. The latter is marked as Beta, I'm not sure how stable it is. But I have requests-kerberos in use for a while without any issue.

Maybe a more stable solution would be https://github.com/brandond/requests-negotiate-sspi, which is using pywin32's SSPI implementation.

Upvotes: 0

liorda
liorda

Reputation: 1572

I found this answer which works great for me because:

  1. I'm only going to run it from Windows, so portability isn't a problem
  2. The response is a simple json document, so no need to store an open session

It's using the WinHTTP.WinHTTPRequest.5.1 COM object to handle authentication natively:

import win32com.client
URL = 'http://bigcorp/tfs/page.aspx'    
COM_OBJ = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
COM_OBJ.SetAutoLogonPolicy(0)
COM_OBJ.Open('GET', URL, False)
COM_OBJ.Send()
print(COM_OBJ.ResponseText)

Upvotes: 11

Andy Li-MSFT
Andy Li-MSFT

Reputation: 30412

NTLM credentials are based on data obtained during the interactive logon process, and include a one-way hash of the password. You have to provide the credential.

Python has requests_ntlm library that allows for HTTP NTLM authentication.

You can reference this article to access the TFS REST API : Python Script to Access Team Foundation Server (TFS) Rest API

If you are using TFS 2017 or VSTS, you can try to use Personal Access Token in a Basic Auth HTTP Header along with your REST request.

Upvotes: -1

Related Questions