使用ADAL验证到Azure API应用程序

本文关键字:API 应用程序 Azure ADAL 验证 使用 | 更新日期: 2023-09-27 17:50:52

我有一个标记为"Public (authenticated)"的Azure API应用程序,并在关联的网关中设置了一个Azure Active Directory标识,详见保护API应用程序。

然后,我在同一个Azure Active Directory租户中创建了一个本机应用程序,并在委托权限中添加了访问网关的权限。

使用ADAL和以下代码,我能够成功验证并获得访问令牌,但我不知道如何使用它来访问我的API应用程序。

string Tenant = "[xxx].onmicrosoft.com";
string Authority = "https://login.microsoftonline.com/" + Tenant;
string GatewayLoginUrl = "https://[gateway].azurewebsites.net/login/aad";
string ClientId = "[native client id]";
Uri RedirectUri = new Uri("[native client redirect url]");
async Task<string> GetTokenAsync()
{
  AuthenticationContext context = new AuthenticationContext(Authority);
  PlatformParameters platformParams = new PlatformParameters(PromptBehavior.Auto, null);
  AuthenticationResult result = await context.AcquireTokenAsync(GatewayLoginUrl, ClientId, RedirectUri, platformParams);
  return result.AccessToken;
}

我已经测试了API应用程序手动输入我在Chrome中获得的x-zumo-auth header,然后它就工作了,但不是我使用ADAL获得的令牌。我也试过在他们的示例代码中描述的浏览器表单,它工作,但没有给我一个刷新令牌。

我需要如何设置我的身份验证码,以便我可以使用TokenCache和ADAL与我的API应用程序?

使用ADAL验证到Azure API应用程序

通常在调用web api时,在授权头中传递访问令牌:

授权:Bearer thisistheaccesstokenyourecievedfrommadal

您可能希望使用AppServiceClient来验证用户并调用受保护的API应用程序端点。安装Microsoft.Azure.AppService SDK (-pre) Nuget包到你的客户端项目。

您可以在GitHub上的AzureCards示例中找到更多详细信息- https://github.com/Azure-Samples/API-Apps-DotNet-AzureCards-Sample