使用oAuth访问Azure DevOps REST API [英] Access Azure DevOps REST API with oAuth

查看:244
本文介绍了使用oAuth访问Azure DevOps REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已在AzureAD中创建了具有"Azure DevOps"权限的应用程序.

I have created my application in AzureAD with the permission "Azure DevOps".

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

Below is my code to fetch project list from 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 .

But I'm getting error as "You are not authorized to access https://dev.azure.com."

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

I am using oAuth 2.0 Client Credential flow to get access token. What could be the reason

推荐答案

通常,当您希望应用程序代表调用用户与Azure DevOps API进行通信而无需提示用户名时,可以使用使用oAuth的REST API和每次输入密码.为此,用户将需要授权应用程序以代表他们与Azure DevOps API通信.

Typically you'd use the REST API using oAuth when you want your application to communicate with Azure DevOps API on behalf of the calling user without having to prompt for usernames and passwords each time. To do this, the user will need to authorize the application to communicate to the Azure DevOps API on their behalf.

在高层,您调用授权"端点并提供回调.回调必须是您应用程序中的安全网址(https):

At a high-level, you call the "authorize" endpoint and provide a callback. The callback must be a secure url (https) in your application:

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中的授权代码重定向到您的回调位置.

Assuming the user accepts the authorization, Azure DevOps redirects to your callback location with the authorization code in the URL.

https://fabrikam.azurewebsites.net/myapp/oauth-callback
    ?code={authorization code}
    &state={state}

获取访问令牌

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

Obtain an Access Token

Now that your application is authorized, you need to obtain an access token:

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

application/x-www-form-urlencoded表单具有以下主体,其中包含创建应用程序时的应用程序密码,用户授权应用程序时刚收到的授权代码以及安全回调.

The application/x-www-form-urlencoded form has the following body with the application secret when you created the application, the authorization code you just received when the user authorized your app, and the secure callback.

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响应中包含访问令牌.

The response will contain the access token in the JSON response.

{
   "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 }
}

请注意,令牌不是永久令牌,可能需要刷新.

Note that the token isn't permanent and may need to be refreshed.

最后,现在您有了用户访问令牌,可以将其包含在对服务器的请求中的授权"标头中.

Lastly, now that you have a user-access token, you can include it in the Authorization header in your requests to the server.

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,请使用个人访问令牌,因为它很容易:

If you're not using a dedicated application and you just want to query the API with credentials you control -- use a Personal Access Token, as it's a lot easier:

httpClient.DefaultRequestHeaders.Authorization =
   new AuthenticationHeaderValue("Basic {base-64-encoded-string of username:PAT}");

这篇关于使用oAuth访问Azure DevOps REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆