调用受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");
}

根据您的指导,我有2个应用程序注册在ActiveDirectory

  1. 服务器应用程序已暴露APIhttps://testapp.azurewebsites.net/Admin/,范围为GetCustomers
  2. Web URI - https://testapp.azurewebsites.net/auth-response和https://testapp.azurewebsites.net

客户端应用程序具有此范围的权限作为Admin,我授予它并创建了一个ClinetSecret

我忘了做什么?史蒂夫。

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

下面是该过程的演练

关于作用域的更多细节

最新更新