【问题标题】:How to write a python script to authenticate to Azure DevOps REST API and get the access token?如何编写 python 脚本对 Azure DevOps REST API 进行身份验证并获取访问令牌?
【发布时间】:2019-10-28 18:56:59
【问题描述】:

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

  • 使用个人访问令牌 (PAT)
  • 使用 OAuth 2.0

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

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

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

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

【问题讨论】:

  • 您好,您有解决这个问题的办法吗?

标签: python api azure-devops azure-devops-rest-api


【解决方案1】:

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

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

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

Tutorial for using requests_oauth2

【讨论】:

  • 我试过你建议的标题。但是发生了同样的错误。
  • 我可以通过标头直接传递个人访问令牌 (PAT) 以访问 azure-devops REST API 吗?
  • @AnjanaDyna,您不能直接通过标头传递个人访问令牌 (PAT) 来访问 azure-devops REST API。如果要使用PAT认证,可以参考这个link
  • 我试过了。可以肯定的是,使用该方法进行的身份验证是成功的。但我无法使用 python 客户端 api 在 azure-devops 中创建新用户。我把它作为一个问题发布在这里:stackoverflow.com/questions/56591886/…。你能帮帮我吗?
  • 您可以尝试删除headers = {'Accept': 'application/json;api-version=1.0'},改用默认值。
猜你喜欢
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 2022-06-12
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 2016-08-10
  • 2017-12-24
相关资源
最近更新 更多