azure-devops - 使用 oAuth 访问 Azure DevOps REST API

标签 azure-devops

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

下面是我从 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 客户端凭证流来获取访问 token 。 可能是什么原因

最佳答案

通常,当您希望您的应用程序代表调用用户与 Azure DevOps API 通信而不必每次都提示输入用户名和密码时,您会使用 oAuth 的 REST API。为此,用户需要授权应用程序代表他们与 Azure DevOps API 通信。

following page provides a good overview of this process .

用户授权您的应用

在较高级别,您调用“授权”端点并提供回调。回调必须是您应用程序中的安全 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}

获取访问 token

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

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

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

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 响应中包含访问 token 。

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

请注意, token 不是永久性的,可能需要刷新。

使用授权 header

最后,既然您拥有用户访问 token ,您可以将其包含在对服务器的请求的授权 header 中。

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

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

关于azure-devops - 使用 oAuth 访问 Azure DevOps REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56527208/

相关文章:

security - 如何在 Azure DevOps 组织中有效处理个人访问 token ?

Azure Devops Pipeline - Angular 13 到 Azure 应用服务错误

azure-devops - Scrum/Visual Studio Team Services 添加自定义容量事件

sql-server - 在 Visual Studio Team Services 中以 Windows 用户身份运行

node.js - 有没有办法为 VSTS CI npm 任务提供环境变量?

powershell - 通过脚本设置管道变量时,Azure DevOps 是否删除引号?

git - 发布分支的 Azure devops merge 类型

linux - 未找到 SSH Shell 命令(composer、npm)

python - 在 VSTS 中构建 Django 应用程序的定义

azure - 在失败的任务上继续 Azure Pipeline