使用个人访问令牌进行Azure Devops API存储库操作

问题描述:

我已经从Azure Devops用户界面生成了一个个人访问令牌,但是无法使用它来针对Devops API发出请求。

I have generated a personal access token from the Azure Devops user interface but am unable to use this to make requests against the Devops API.

我尝试了许多不同的方法标头字段,但我总是被重定向到登录页面,好像我没有经过身份验证一样。

I have tried many different header fields, but I am always redirected to the log in page as though I hadn't authenticated.

token = #Token generated on Devops project page
token_bytes = token.encode('utf-8')
token64 = base64.b64encode(token_bytes)
authorization_string = "basic " + str(token64)

repo_endpoint_url = "https://dev.azure.com/{organization}/{project}/_apis/git/repositories?api-version=5.1".format(organization=organization, project=project)

headers = {"Content-Type" : "application/json", "Authorization" : authorization_string}

response = requests.get(repo_endpoint_url, headers)

登录页面HTML的响应始终为203。这是我希望看到的是否标头中没有访问令牌。

response is always 203 with login page HTML. This is what I'd expect to see if I didn't have an access token in the header.

我尝试使用 Bearer代替 basic,我尝试添加{username}:{token}和其他许多小调整。

I have tried, "Bearer" instead of "basic", I have tried adding {username}:{token}, and many other little tweaks.

我在做什么错了?

我只是剪贴了下面对我有用的代码:

I just scrapbooked following code which worked for me:

import requests
import base64

repo_endpoint_url = "https://dev.azure.com/<organization>/<project>/_apis/git/repositories?api-version=5.1"

username = "" # This can be an arbitrary value or you can just let it empty
password = "<your-password-here>"
userpass = username + ":" + password
b64 = base64.b64encode(userpass.encode()).decode()
headers = {"Authorization" : "Basic %s" % b64} 

response = requests.get(repo_endpoint_url, headers=headers)
print(response.status_code) # Expect 200