python - 如何编写 python 脚本对 Azure DevOps REST API 进行身份验证并获取访问令牌?
问题描述
如何在 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
auth URL 是正确的,因为当我尝试在浏览器中访问相同的 URL 时,它成功地重定向到表单以输入 azure 用户凭据。
脚本的预期行为是,当请求 auth_url 时,Azure DevOps Services 应要求用户授权。我认为这应该通过在终端/通过浏览器提示输入用户名和密码来完成。
我对 python 脚本和 REST API 完全陌生。有人可以通过指出我的代码中的错误或指向一些示例来帮助我吗?
解决方案
http 错误 203 表示返回的元信息不是来自具有对象副本的服务器的对象的确定集,而是来自私有覆盖网络。在您的代码中,您添加了headers = {'Accept': 'application/json;api-version=1.0'}
,但实际上内容类型应该是application/x-www-form-urlencoded
.
您可以使用一些用于 python 的 OAuth2 库对 Azure DevOps REST API 进行身份验证,例如OAuthLib。它包括几个样本。
另外,您可以参考以下主题,希望对您有所帮助。
推荐阅读
- vuejs2 - Vue递归渲染tr数组
- android - 从活动结果返回时如何避免黑屏?
- javascript - 无法在屏幕焦点上重新渲染功能
- c# - 你可以从另一个类中获取一个类中的方法中的变量值吗?
- sql-server-2012 - 如何处理 SQL Server 数据库中的大量 XML 数据
- python - 使用 TensorFlow.js 模型转换器的 Keras 转换模型。:错误:无法识别的参数:\ 文件夹
- ibm-cloud - 如何通过 Softlayer Rest API 使用 IBM 云获取任何资源的订单状态?
- sql - 按同一列分组,但以两种不同的方式聚合
- python - 两天之间的差异(不包括周末)(以小时为单位)
- distributed-computing - 现实生活中何时有人会选择可用性而不是一致性(谁会对过时的数据感兴趣?)