使用oAuth访问Azure DevOps REST API

4

我已经在AzureAD中创建了我的应用程序,并使用权限“Azure DevOps”。

下面是我从Azure DevOps获取项目列表的代码:

 using (HttpClient client = new HttpClient())
            {

                HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://login.microsoftonline.com/21d63aec-6502-4638-98f3-04587e69d53b/oauth2/v2.0/token");
                requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                Dictionary<String, String> form = new Dictionary<String, String>()
            {
                { "grant_type", "client_credentials" },
                { "client_id", "ac313ad2...." },
                { "scope", "https://app.vssps.visualstudio.com/.default" },
                { "client_secret", "BX0RldhqL...." }
            };
                requestMessage.Content = new FormUrlEncodedContent(form);

                HttpResponseMessage responseMessage = client.SendAsync(requestMessage).Result;

                if (responseMessage.IsSuccessStatusCode)
                {
                    String body = responseMessage.Content.ReadAsStringAsync().Result;

                    JsonConvert.PopulateObject(body, tokenModel);

                }
            }


using (ProjectHttpClient projectHttpClient = new ProjectHttpClient(new Uri("https://dev.azure.com/AlfabetChennaiDev"), new VssOAuthAccessTokenCredential(tokenModel.AccessToken)))
            {
                IEnumerable<TeamProjectReference> projects = projectHttpClient.GetProjects().Result;
            }

但是我遇到了错误,提示“您没有权限访问https://dev.azure.com”。

我使用的是oAuth 2.0客户端凭据流来获取访问令牌。可能的原因是什么?


当我使用Google搜索时,在微软开发者社区上偶然发现了这些帖子,也许可以帮到您。它们提出了一些建议。https://developercommunity.visualstudio.com/content/problem/370982/vs30063-you-are-not-authorized-to-access-azure-dev.html https://developercommunity.visualstudio.com/content/problem/222842/rest-api-unable-to-log-on-vssps-accountvsspsvisual.html - fluidguid
对于您现在已删除的问题,https://dev59.com/dmw15IYBdhLWcg3wu-M9。请考虑在某个时候进行编辑和取消删除。 - xdtTransform
1个回答

7
通常情况下,当您想让您的应用程序代表调用用户与 Azure DevOps API 进行通信而不必每次提示输入用户名和密码时,您会使用 oAuth 使用 REST API。要实现这一点,用户需要授权应用程序代表他们与 Azure DevOps API 进行通信。

以下页面提供了该过程的概述

用户授权您的应用程序

在高层次上,您调用“authorize”端点并提供回调。回调必须是应用程序中安全的 URL (https):

https://app.vssps.visualstudio.com/oauth2/authorize
    ?client_id={app ID}
    &response_type=Assertion
    &state={state}
    &scope={scope}
    &redirect_uri={callback URL}

假设用户接受授权,Azure DevOps 将在 URL 中携带授权代码重定向到您指定的回调位置。
https://fabrikam.azurewebsites.net/myapp/oauth-callback
    ?code={authorization code}
    &state={state}

获取访问令牌

现在您的应用程序已经获得了授权,您需要获取访问令牌:

POST https://app.vssps.visualstudio.com/oauth2/token

该表单的 body 是 application/x-www-form-urlencoded,它包含了创建应用时的应用密钥、用户授权你的应用后刚刚接收到的授权码以及安全回调。
public string GenerateRequestPostData(string appSecret, string authCode, string callbackUrl)
{
   return String.Format("client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion={0}&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion={1}&redirect_uri={2}",
           HttpUtility.UrlEncode(appSecret),
           HttpUtility.UrlEncode(authCode),
           callbackUrl
    );
}

响应将在JSON响应中包含访问令牌。
{
   "access_token": { access token for the user },
   "token_type": { type of token },
   "expires_in": { time in seconds that the token remains valid },
   "refresh_token": { refresh token to use to acquire a new access token }
}

请注意,令牌不是永久的,可能需要刷新。
使用授权标头
最后,现在您拥有用户访问令牌,可以将其包含在请求服务器时的授权标头中。
GET https://dev.azure.com/myaccount/myproject/_apis/build-release/builds?api-version=3.0
Authorization: Bearer {access_token}

例如:

httpClient.DefaultRequestHeaders.Authorization =
   new AuthenticationHeaderValue("Bearer", "{access_token}");

如果您没有使用专用应用程序,只想使用您自己控制的凭据查询API,则可以使用个人访问令牌,因为这样更容易:
httpClient.DefaultRequestHeaders.Authorization =
   new AuthenticationHeaderValue("Basic {base-64-encoded-string of username:PAT}");

这个正常工作。那么DevOps不支持客户端凭据流获取访问令牌吗? - balaji
这真的取决于你想做什么。以下是许多不同类型的身份验证流程的详细介绍:https://learn.microsoft.com/zh-cn/azure/devops/integrate/get-started/authentication/authentication-guidance?view=azure-devops - bryanbcook
正确。我正在使用oAuth,oAuth有不同的授权类型。你的解决方案是基于授权代码,但我正在尝试使用客户端凭据。 https://oauth.net/2/ - balaji
@bryanbcook你能帮我解决下载文件问题吗?问题链接。非常感谢你的帮助。 - user13812143
我在尝试使用POST请求访问 https://app.vssps.visualstudio.com/oauth2/token 时遇到了400错误。还有其他人也遇到同样的情况吗? - drethedevjs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接