首页 > 解决方案 > 调用受 Azure Active Directory 保护的 WebService

问题描述

我已将 Web 应用程序部署到 Azure 应用服务并设置应用服务身份验证以使用 Active Directory。

在控制台应用程序中,我有以下代码。

string baseUrl = "https://testapp.azurewebsites.net/Admin/GetCustomers";
string sAuthority = "https://login.microsoftonline.com/{tennant ID}“;
string sClient = “{“Client ID};
string sClientSecret = “{“ClientSecret};


IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(sClient)
          .WithClientSecret(sClientSecret)
          .WithAuthority(new Uri(sAuthority))
          .Build();

string[] scopes = new string[] { "https://testapp.azurewebsites.net/Admin/.default" }; 
         
AuthenticationResult result = null;
result =  app.AcquireTokenForClient(scopes).ExecuteAsync().Result;

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = httpClient.GetAsync(baseUrl).Result;

if (response.IsSuccessStatusCode)
{
    string json = response.Content.ReadAsStringAsync().Result;
    JObject resultData = JsonConvert.DeserializeObject(json) as JObject;
    Console.WriteLine("Finished Loading Data!");
}
else
{
     Console.WriteLine("Error Happened");
}

根据您的指南,我在 ActiveDirectory 中注册了 2 个应用程序

  1. 服务器应用程序具有公开的 API https://testapp.azurewebsites.net/Admin/范围为 GetCustomers
  2. Web URI - https://testapp.azurewebsites.net/auth-responsehttps://testapp.azurewebsites.net

客户端应用程序对此范围具有权限作为管理员我授予它并创建了一个 ClinetSecret

我忘了做什么?史蒂夫

标签: c#azuremicrosoft-identity-platform

解决方案


这不起作用,因为您正在获取图形 api 范围的令牌:

string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
result =  app.AcquireTokenForClient(scopes).ExecuteAsync().Result;

如果您改为调用图形 api,则从该调用返回的令牌将起作用:

string baseUrl = "https://graph.microsoft.com/v1/me"

但这不是你所追求的。您需要做的是创建一个范围,该范围提供对您的 API 的访问,以便 AAD 可以发出适当的令牌。

为此,您需要在管理托管 API 的 Web 应用程序时在 Azure 门户中“公开 API”。您可以使用您创建的自定义命名范围,或者[app id uri]/.default改为使用。

这是该过程的演练

有关范围的更多详细信息


推荐阅读