问题
I am trying to access TFS
REST API in Python
2 but getting 401 Authorization Error
. I am able to access API url from web-browser
using same credentials. Also same credentials is working with .Net
code. Tried with urllib2 library as guided in this solution. Any suggestion to access TFS api in Python2?
tfs.py
import requests
from requests.auth import HTTPDigestAuth
username = '<UserName>'
password = '<Password>'
tfsApi = 'https://{myserver}/tfs/collectionName/_apis/projects?api-version=2.0'
tfsResponse = requests.get(tfsApi, auth=(username, password))
if(tfsResponse.ok):
tfsResponse = tfsResponse.json()
print(tfsResponse)
else:
tfsResponse.raise_for_status()
Error:
Traceback (most recent call last):
File "D:\Scripts\tfs.py", line 13, in <module>
tfsResponse.raise_for_status()
File "C:\Python27\lib\site-packages\requests\models.py", line 862, in raise_fo
r_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://{myserver}/tfs/collectionName/_apis/projects?api-version=2.0
.Net Working code:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", AppConfig.TFS_API_USER, AppConfig.TFS_API_PASS))));
回答1:
TFS uses NTLM authentication protocol , Hence I have to update my code with HTTP NTLM authentication using the requests library.
Working code:
import requests
from requests_ntlm import HttpNtlmAuth
username = '<DOMAIN>\\<UserName>'
password = '<Password>'
tfsApi = 'https://{myserver}/tfs/collectionName/_apis/projects?api-version=2.0'
tfsResponse = requests.get(tfsApi,auth=HttpNtlmAuth(username,password))
if(tfsResponse.ok):
tfsResponse = tfsResponse.json()
print(tfsResponse)
else:
tfsResponse.raise_for_status()
回答2:
- It seems you want to get a list of team projects with REST API. The API should look like:
-
http://tfsserver:8080/tfs/CollectionName/_apis/projects?api-version=1.0
Make sure you have enabled Basic Auth for your TFS:
- check your IIS to see whether the Basic authentication service role is installed.
- go to IIS Manager, select Team Foundation Server -- Authentication and disable everything other than Basic Authentication. Then do the same for the tfs node under Team Foundation Server.
- restart your IIS.
来源:https://stackoverflow.com/questions/40146361/tfs-rest-api-authorization-issue-in-python-2