如何在 python 脚本中对 Azure DevOps REST API 进行身份验证? 我发现有两种方法:
- 使用个人访问 token (PAT)
- 使用 OAuth 2.0
我用的是第二种方法。按照本文档中的步骤操作: https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops
我编写此函数是为了使用 OAuth 2.0 向 azure DevOps 进行授权:
def get_authenticated():
client_id = < my client ID as a string >
state = "user1"
scope = "vso.graph_manage%20vso.identity_manage%20vso.profile_write%20vso.project_manage%20vso.tokenadministration%20vso.tokens"
callback_URL = < Callback URL to my azure devops account >
# Azure DevOps Services authorization endpoint
Auth_URL = "https://app.vssps.visualstudio.com/oauth2/authorize?client_id=" + client_id + "&response_type=Assertion&state=" + state + "&scope=" + scope + "&redirect_uri=" + callback_URL
headers = {'Accept': 'application/json;api-version=1.0'}
print(Auth_URL)
response = requests.get(Auth_URL,headers = headers)
print(response)
print(response.status_code)
print(response.headers['content-type'])
response.raise_for_status()
但是当调用这个函数时,我得到的输出是:
<Response [203]>
203
text/html; charset=utf-8
身份验证 URL 是正确的,因为当我尝试在浏览器中访问相同的 URL 时,它成功重定向到表单以输入 azure 用户凭据。
脚本的预期行为是,当请求 auth_url 时,Azure DevOps Services 应要求用户授权。我认为这应该通过在终端/通过浏览器提示输入用户名和密码来完成。
我对 python 脚本和 REST API 完全陌生。 有人可以通过指出我的代码中的错误或指出一些示例来帮助我吗?
最佳答案
http 错误 203 表示返回的元信息不是来自具有对象副本的服务器的对象的确定集,而是来自私有(private)覆盖网络。在您的代码中,您添加了 headers = {'Accept': 'application/json;api-version=1.0'}
,但实际上内容类型应该是 application/x-www-表单 urlencoded
.
您可以使用一些适用于 python 的 OAuth2 库来向 Azure DevOps REST API 进行身份验证,例如 OAuthLib 。它包括几个样本。
另外,您可以引用以下主题,希望对您有所帮助。
关于python - 如何编写 python 脚本来向 Azure DevOps REST API 进行身份验证并获取访问 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56593061/