首页 > 解决方案 > 如何编写 python 脚本对 Azure DevOps REST API 进行身份验证并获取访问令牌?

问题描述

如何在 python 脚本中对 Azure DevOps REST API 进行身份验证?我发现有两种方法:

我正在使用第二种方法。遵循本文档中的步骤: https ://docs.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

auth URL 是正确的,因为当我尝试在浏览器中访问相同的 URL 时,它成功地重定向到表单以输入 azure 用户凭据。

脚本的预期行为是,当请求 auth_url 时,Azure DevOps Services 应要求用户授权。我认为这应该通过在终端/通过浏览器提示输入用户名和密码来完成。

我对 python 脚本和 REST API 完全陌生。有人可以通过指出我的代码中的错误或指向一些示例来帮助我吗?

标签: pythonapiazure-devopsazure-devops-rest-api

解决方案


http 错误 203 表示返回的元信息不是来自具有对象副本的服务器的对象的确定集,而是来自私有覆盖网络。在您的代码中,您添加了headers = {'Accept': 'application/json;api-version=1.0'},但实际上内容类型应该是application/x-www-form-urlencoded.

您可以使用一些用于 python 的 OAuth2 库对 Azure DevOps REST API 进行身份验证,例如OAuthLib。它包括几个样本。

另外,您可以参考以下主题,希望对您有所帮助。

requests_oauth2 使用教程


推荐阅读