【问题标题】:TFS Rest Api authorization issue in Python 2Python 2 中的 TFS Rest Api 授权问题
【发布时间】:2017-08-02 17:48:56
【问题描述】:

我试图在Python 2 中访问TFS REST API,但得到401 Authorization Error。我可以使用相同的凭据从 web-browser 访问 API url。同样的凭据也适用于.Net 代码。按照this solution 的指导尝试使用 urllib2 库。在 Python2 中访问 TFS 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))));

【问题讨论】:

  • 您使用本地 TFS 还是 VSTS?您使用的是哪个版本的 TFS?
  • 我正在使用Microsoft Visual Studio Team Foundation Server,版本:14.95.25229.0

标签: python rest tfs


【解决方案1】:

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

【讨论】:

  • 当然。谢谢@Cece-MSFT
  • 域名+用户名是什么样的?你能给我一个假的例子吗?
【解决方案2】:
  1. 看来你想get a list of team projects 使用 REST API。 API 应如下所示:

-

http://tfsserver:8080/tfs/CollectionName/_apis/projects?api-version=1.0
  1. 确保您已为您的 TFS 启用基本身份验证:

    • 检查你的 IIS 看是否有 Basic 身份验证服务角色 已安装。
    • 进入 IIS 管理器,选择 Team Foundation Server -- 身份验证 并禁用基本身份验证以外的所有内容。然后做 Team Foundation Server 下的 tfs 节点也是如此。
    • 重新启动 IIS。

【讨论】:

  • 感谢您的回复。我已将 API url 中的 api-version 更改为 1.0,但仍然是同样的问题。
  • 您似乎使用的是 TFS 2015。您是否按照我发布的内容为您的 TFS 启用了基本身份验证?
  • 另外,如果您未设置 SSL,则本地服务器的 url 通常以 http 开头。
  • 我们在服务器上启用了 SSL。同时启用基本身份验证。但不知何故,它不适用于请求模块。
  • 非常感谢您的帮助。我得到了解决方案。我已经发布作为答案。可能会对其他人有所帮助。
猜你喜欢
  • 2019-07-05
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多