Python 2 中的 TFS Rest Api 授权问题 [英] TFS Rest Api authorization issue in Python 2

查看:69
本文介绍了Python 2 中的 TFS Rest Api 授权问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问 Python 2 中的 TFS REST API,但收到 401 授权错误.我可以使用相同的凭据从 web-browser 访问 API url.同样的凭据也适用于 .Net 代码.按照此解决方案中的指导尝试使用 urllib2 库.在 Python2 中访问 TFS api 有什么建议吗?

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

错误:

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 使用 NTLM 身份验证协议 ,因此我必须使用 请求 库.

TFS uses NTLM authentication protocol , Hence I have to update my code with HTTP NTLM authentication using the requests library.

工作代码:

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

这篇关于Python 2 中的 TFS Rest Api 授权问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆