我正在尝试获取 jwt 访问 token 来调用一些 azure devops API 端点。
我首先通过oauth端点获取代码:
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 权限,如下所示:
为了获取授权代码,我在获取 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
值,如下所示:
我通过 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
回应:
当我使用上面的访问 token 调用以下DevOps API时,我成功收到了如下响应:
GET https://dev.azure.com/<orgname>/_apis/git/repositories?api-version=2.0
回应:
要调用 Microsoft Graph,您需要将范围值更改为https://graph.microsoft.com/.default
,同时获取访问 token 。
关于azure - 如何通过 azure 应用程序访问 azure devops api?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76377820/