【问题标题】:Calling WebService protected by Azure Active Directory调用受 Azure Active Directory 保护的 WebService
【发布时间】:2021-02-13 01:54:10
【问题描述】:

我已将 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# azure microsoft-identity-platform


    【解决方案1】:

    这不起作用,因为您正在获取图形 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

    Here is a walkthrough of the process

    More detail on scopes

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2017-11-05
    • 2016-08-14
    • 2017-08-29
    • 2017-11-25
    • 1970-01-01
    • 2018-06-27
    相关资源
    最近更新 更多