使用 Azure Devops rest API 的访问令牌

问题描述 投票:0回答:1

我正在尝试使用 devops Rest API 来处理管道。

我正在请求一个访问令牌,然后使用它来发出 devops 发布请求。

        string orgName = "MyOrg";
        string project = "MyProject";
        string tenantId = "0eb...";
        string authority = $"https://login.microsoftonline.com/{tenantId}";
        string clientId = "656...";
        string clientSecret = "n.C...";
        string scope = "499b84ac-1321-427f-aa17-267ca6975798/.default"; // Azure DevOps access scope

        var app = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithClientSecret(clientSecret)
            .WithAuthority(new Uri(authority))
            .Build();

        var result = await app.AcquireTokenForClient(new[] { scope }).ExecuteAsync();
        string accessToken = result.AccessToken;

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

        HttpResponseMessage response2 = await client.GetAsync($"https://dev.azure.com/{orgName}/{project}/_apis/pipelines?api-version=7.0");
        string responseBody = await response2.Content.ReadAsStringAsync();

在 Azure 门户 Active Directory 刀片中,我注册了一个应用程序,并使用概述页面中列出的目录(租户)ID 作为

tenantId
。在 Certificates & secrets 子菜单中,我创建了一个客户端密钥,并使用值作为
clientId
和密钥 ID 作为
clientSecret
。我的理解是范围
499b84ac-1321-427f-aa17-267ca6975798/.default
是一个硬编码的 guid,它解析为所有 devops 权限。

我收到这个回复:

TF401444: Please sign-in at least once as {tenantId}\\\\{tenantId}\\\\{guid I dont recognize} in a web browser to enable access to the service.\",\"typeName\":\"Microsoft.TeamFoundation.Framework.Server.UnauthorizedRequestException, Microsoft.TeamFoundation.Framework.Server\",\"typeKey\":\"UnauthorizedRequestException\",\"errorCode\":0,\"eventId\":3000}"

我不明白我在这里错过了什么。为什么要求我登录?令牌是否足以授权我的 api 请求?我的目标是让 API 服务能够与管道一起工作。任何帮助将不胜感激。

c# asp.net azure azure-devops azure-active-directory
1个回答
0
投票

您的应用程序注册需要具有访问 Devops REST API 的权限。这是在应用程序注册的 API 权限部分中配置的。看起来您也在尝试使用客户端凭证流(客户端 ID 和密码)。

查看门户,似乎应用程序权限(客户端凭据流需要)可用于 Azure Devops,因此这种方法行不通。

你有两个选择:

  1. 在网络应用程序中,使用委托权限和登录用户的安全上下文

  2. 在您的 REST 调用中使用 PAT(个人访问令牌)和基本身份验证标头。

© www.soinside.com 2019 - 2024. All rights reserved.