【问题标题】:Authenticate Web App against API App using Azure AD bearer token使用 Azure AD 不记名令牌针对 API 应用对 Web 应用进行身份验证
【发布时间】:2016-11-15 19:00:08
【问题描述】:

我正在尝试访问我在 Azure 上托管并使用 Azure AD 保护的 API 应用程序。

对于 API 应用,我设置了应用服务身份验证 = Azure Active Directory“快速”管理模式。

在“经典”门户中,我在 AD 下创建了几个应用程序。一个用于 API 应用程序,另一个用于 Web 应用程序。对于 Web 应用程序,我在 API 应用程序的“其他应用程序的权限”下添加了一个条目(尽管我不确定我是否需要这个,因为 API 应用程序的“访问应用程序所需的用户分配”已关闭)。我还为 Web App 生成了一个密钥。

按照此处给出的示例代码 - https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-oauth2-appidentity ...

我可以使用以下代码成功获取不记名令牌:

private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"];

static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

private static string ApiId = ConfigurationManager.AppSettings["ApiId"];

private static AuthenticationContext authContext = new AuthenticationContext(authority);
private static ClientCredential clientCredential = new ClientCredential(clientId, appKey);

...

AuthenticationResult result = null;
int retryCount = 0;
bool retry = false;

do
{
    retry = false;
    try
    {
        // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
        result = await authContext.AcquireTokenAsync(ApiId, clientCredential);
    }
    catch (AdalException ex)
    {
        if (ex.ErrorCode == "temporarily_unavailable")
        {
            retry = true;
            retryCount++;
            Thread.Sleep(3000);
        }
    }

} while ((retry == true) && (retryCount < 3));

if (result == null)
    return Request.CreateResponse(HttpStatusCode.InternalServerError, "Could not authenticate against API.");

但是当我将不记名令牌与从 Web 应用程序到 API 应用程序的请求一起使用时,我总是收到 401 未经授权的响应:

StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date: Wed, 13 Jul 2016 08:43:09 GMT
  Server: Microsoft-IIS/8.0
  WWW-Authenticate: Bearer realm="MY-API-APP-ID-IS-HERE"
  X-Powered-By: ASP.NET
  Content-Length: 58
  Content-Type: text/html
}

这是我用来发出 401 失败请求的代码:

var apiUri = new Uri(ConfigurationManager.AppSettings["ApiUrl"] + "/api/MethodImCalling");
var client = new RestClient(apiUri.GetLeftPart(UriPartial.Authority));
var request = new RestRequest(apiUri, Method.GET);
request.AddHeader("Authorization", "Bearer " + result.AccessToken);
request.AddParameter("something", somevalue);
var response = client.Execute(request);

if (response.StatusCode != HttpStatusCode.OK)
    return Request.CreateResponse(response.StatusCode); // Relay non-successful response

任何想法我可能做错了什么或遗漏了什么?提前致谢!

我已经有 Azure 中的逻辑应用程序可以毫无问题地访问 API 应用程序,但我注意到逻辑应用程序 json 中的身份验证凭据包含一个“受众”参数。上面的代码没有使用“观众”,所以这可能是谜题中缺少的部分,如果是,我该如何添加它?

显示如何配置 Web 应用以访问 API 应用的屏幕截图:

【问题讨论】:

  • 您能否分享一下您如何配置 API 以进行授权的详细信息?
  • @PhilippeSignoret - 我正在使用 App Service Authenication = Azure Active Directory“Express”管理模式(也将添加到问题中)。这是你追求的细节吗?不知道要提供什么其他细节。干杯。
  • 在部署到 Azure 之前,示例代码在您的本地是否可以正常工作?如果访问令牌不允许您访问您的 API,我建议您使用 JWT 解码工具来分析令牌,这里是 JWT 解码的网页:jwt.io
  • @Jambor-MSFT - 不幸的是,该代码在本地或 Azure 上不起作用。干杯。
  • 您能否添加一个屏幕截图,说明您如何设置 Web 应用的“其他应用程序的权限”?

标签: azure oauth azure-web-app-service azure-active-directory bearer-token


【解决方案1】:

您收到 401 响应的原因是您只授予了您的应用程序 Delegated Permissions,但您正在使用需要 Application Permissions 的客户端凭据流。

您可以更改代码以使用授权代码流程,也可以将应用程序权限从您的网络应用授予您的网络 API。

要使用授权代码流程,您需要将代码更改为使用 AcquireTokenByAuthorizationCodeAsync。

您可以在此处找到有关这两种不同方法的更多信息: https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/#web-application-to-web-api

【讨论】:

  • 感谢萨卡的指点。我正在尝试根据您的指示实施解决方案。有点学习曲线,因为有一点需要绕开我的脑袋。一旦我弄清楚了,我会把它标记为答案。我从 Microsoft 找到了一些代码示例可供探索,但我想我会尝试触发“或将应用程序权限从您的 Web 应用程序授予您的 Web API”选项,因为这听起来像是纯粹的配置。
  • 我真的在为此苦苦挣扎。我确定这很简单,但是我在哪里“将应用程序权限从您的网络应用程序授予您的网络 API”?
猜你喜欢
  • 1970-01-01
  • 2017-04-08
  • 2017-08-07
  • 2017-08-16
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
相关资源
最近更新 更多