azure - 如何通过 azure 应用程序访问 azure devops api?

标签 azure azure-devops oauth-2.0

我正在尝试获取 jwt 访问 token 来调用一些 azure devops API 端点。

我首先通过oauth端点获取代码:

https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize?client_id=CLIENT_ID&response_type=code&prompt=select_account&scope=CLIENT_ID/.default&redirect_uri=https://foo.bar.com/auth

CLIENT_ID/.default == user_impersonation 和 用户.阅读

这会返回一个code

然后我使用此代码向以下位置发出发布请求:

https://login.microsoftonline.com/organizations/oauth2/v2.0/token

grant_type:authorization_code
client_id:CLIENT_ID
client_secret:SECRET
scope:CLIENT_ID/.default
redirect_uri:https://foo.bar.com/auth
code:CODE

这会返回一个access_token 。然而这个访问 token 似乎并不能做太多事情。

我已经尝试过 https://graph.microsoft.com/v2.0/me/ (它总是返回 Access token validation failure. Invalid audience. )和 https://dev.azure.com/paradime-io/_apis/git/repositories?api-version=2.0 (只是 html 供我登录)- 都使用 Authorization: Bearer {access_token}标题,但它们不起作用。

我也尝试过将它与 git clone... 一起使用用户名和密码,但这也不起作用。

我也尝试过使用on_behalf_of/token端点:

grant_type:urn:ietf:params:oauth:grant-type:jwt-bearer
client_id:CLIENT_ID
client_secret:SECRET
scope:CLIENT_ID/.default
//client_assertion_type:urn:ietf:params:oauth:client-assertion-type:jwt-beare
requested_token_use:on_behalf_of
assertion:CODE

但是返回了access_token在其他 API 端点上也无法使用。

最佳答案

要通过 Azure AD 应用程序访问 Azure DevOps API,您需要使用 499b84ac-1321-427f-aa17-267ca6975798/.default 生成 jwt 访问 token 范围。

我注册了一个 Azure AD 应用程序并添加了 API 权限,如下所示:

enter image description here

为了获取授权代码,我在获取 token 之前在浏览器中运行了以下授权请求:

https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/authorize
?client_id=<appID>
&response_type=code
&redirect_uri=https://jwt.ms
&response_mode=query
&scope=499b84ac-1321-427f-aa17-267ca6975798/.default
&state=12345

当我在浏览器中运行上述请求时,我在地址栏中成功获得了 code 值,如下所示:

enter image description here

我通过 Postman 成功使用授权代码流生成了访问 token ,方法是将上述代码包含在以下请求中:

POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
grant_type:authorization_code
client_id: <appID>
client_secret: <secret>
scope: 499b84ac-1321-427f-aa17-267ca6975798/.default
code: <paste_code_from_above_request>
redirect_uri: https://jwt.ms

回应: enter image description here

当我使用上面的访问 token 调用以下DevOps API时,我成功收到了如下响应:

GET https://dev.azure.com/<orgname>/_apis/git/repositories?api-version=2.0

回应:

enter image description here

要调用 Microsoft Graph,您需要将范围值更改为https://graph.microsoft.com/.default,同时获取访问 token 。

关于azure - 如何通过 azure 应用程序访问 azure devops api?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76377820/

相关文章:

spring-security - Apache Oltu Spring Security OAuth2 和 Google 集成

Spring Boot OAuth2 提供者数据库表解释

c# - C# 连接数据库出错

azure-devops - 从项目中获取所有工作项 azure devops REST API

git - 在 cPanel 上克隆 Azure 存储库

azure-devops - 如何将自定义 dll 从私有(private)存储库添加到 azure dev ops 管道?

azure - 如何定义具有 2 个管道的 MS 托管代理的并行性

spring-security - "Access is denied (user is not anonymous)"与 spring-security-oauth2

Azure FTP 任务突然失败

azure - 逻辑应用发布到 Microsoft Teams 的数据未显示在字段中