2016-10-20 20 views
1

我試圖訪問TFSPython 2中的REST API,但獲取401 Authorization Error。我可以使用相同的憑據從web-browser訪問API網址。代碼也與.Net相同。在this solution的指導下嘗試使用urllib2庫。任何建議在Python2中訪問TFS api?Python 2中的TFS Rest Api授權問題

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() 

錯誤:

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的代碼:

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)))); 
+0

你內部部署TFS或VSTS使用?你使用的是哪個版本的TFS? –

+0

我正在使用Microsoft Visual Studio Team Foundation Server版本:14.95.25229.0 – Roopendra

回答

2

TFS使用NTLM authentication protocol,因此,我必須使用requests庫來更新我的HTTP NTLM身份驗證碼。

工作代碼:

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() 
+0

當然。謝謝@ Cece-MSFT – Roopendra

+1

@BioGeek感謝您的編輯。 – Roopendra

+0

域名+用戶名是什麼樣的?你能給我一個假的例子嗎? – Elliptica

1
  1. 看來你婉t改爲使用REST API的get a list of team projects。該API應該像這樣:

-

http://tfsserver:8080/tfs/CollectionName/_apis/projects?api-version=1.0 
  • 請確認您已經啓用了基本驗證了您的TFS:

    • 檢查你的IIS查看是否安裝了基本身份驗證服務角色 。
    • 轉到IIS管理器,選擇團隊基礎服務器 - 身份驗證 並禁用基本身份驗證以外的所有其他操作。然後在Team Foundation Server下執行 相同的tfs節點。
    • 重新啓動您的IIS。
  • enter image description here

    enter image description here

    +0

    感謝您的回覆。我在API網址中將api-version更改爲了'1.0',但仍然是同樣的問題。 – Roopendra

    +0

    看來你正在使用TFS 2015.你是否已經爲我的TFS啓用了基本身份驗證? –

    +0

    另外,如果您沒有設置SSL,則URL通常以內部部署服務器的http開頭。 –