代码之家  ›  专栏  ›  技术社区  ›  Geoff

从Microsoft Identify Platform获取访问令牌

  •  0
  • Geoff  · 技术社区  · 2 年前

    我已经创建了一个ASP。NET Framework应用程序使用标准模板中的Microsoft Identify Platform,并使用机密客户端获取访问令牌。我现在想使用此访问令牌调用Azure DevOps REST API。

    我的设想是:

    1. 打开应用程序并立即被要求登录
    2. 从机密客户端获取访问令牌
    3. 执行对Azure DevOps的API调用(例如GET https://dev.azure.com/{organization}/_apis/projects )

    我相信我已经完成了步骤1和2(下面的代码),但当我执行API is时,它不会返回结果,只是一个HTML页面要求我登录

    访问令牌从以下代码中恢复:

    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
            {
                var authCode = context.Code;
    
                var tenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                var authority = aadInstance + tenantId;
    
                //string[] scopes = new string[] { "https://graph.microsoft.com/User.Read" };
                string[] scopes = new string[] { "https://app.vssps.visualstudio.com/user_impersonation" };
                //string[] scopes = new string[] { "https://graph.microsoft.com/User.Read", "https://app.vssps.visualstudio.com/user_impersonation" };
    
                // Get the access token from the ConfidentialClientApplication)
                IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
                    .WithRedirectUri(redirectUri)
                    .WithClientSecret(clientSecret)
                    .WithAuthority(authority)
                    .Build();
    
                var authResult = await app.AcquireTokenByAuthorizationCode(scopes, authCode).ExecuteAsync();
    
                string accessToken = authResult.AccessToken;
                Debug.WriteLine($"Access Token: {accessToken}");
    
                //await GetProfileData(accessToken);
                await GetProjectList(accessToken);
            }
    
    

    如果我运行它,我会得到访问令牌,但在API调用中使用它作为承载令牌是行不通的。调用API的方法如下:

    private async Task GetProjectList(string accessToken)
            {
                // Get the Project List from the Azure DevOps API
                var httpClient = new HttpClient();
                var httpRequest = new HttpRequestMessage(HttpMethod.Get,
                    "https://dev.azure.com/gp-ementris/_apis/projects");
    
                httpRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
                    "Bearer", accessToken);
    
                var response = await httpClient.SendAsync(httpRequest);
    
                if (response.IsSuccessStatusCode)
                {
                    Debug.WriteLine(await response.Content.ReadAsStringAsync());
                }
            }
    

    有人能帮我解释一下如何让API使用令牌吗?

    谢谢

    0 回复  |  直到 2 年前