使用 AAD 对 Azure API 应用程序进行身份验证时出现 401 错误

401 error when authenticating to an Azure API App using AAD(使用 AAD 对 Azure API 应用程序进行身份验证时出现 401 错误)
本文介绍了使用 AAD 对 Azure API 应用程序进行身份验证时出现 401 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个 API 应用程序在网关主机上运行良好,现在网关主机已被弃用,我正在尝试遵循 迁移指南.我已经使用 2.8.1 SDK 重新部署了我的服务,并且可以使用 AAD 或 Microsoft 帐户使用浏览器登录该服务,并使用 Swagger 测试该服务.但是,我试图让客户端使用 ClientId 和 Secret 访问服务.该代码能够从 AAD 获取访问令牌,但每当我尝试访问其中一项服务资源时,总是会收到 401 错误.

I have an API app that has been working fine with a Gateway Host and now that the gateway host is being deprecated I'm trying to follow the Migration Guide. I've redeployed my service using the 2.8.1 SDK and can log into the service with a browser using AAD or a Microsoft account and use Swagger to test the service. However, I'm trying to get a client to access the service using a ClientId and Secret. The code is able to get the access token from AAD but I always get a 401 error whenever I try to access one of the service resources.

当我调试服务时,我在日志中看到以下内容:

When I debug the service I see the following in the log:

Microsoft.Azure.AppService.Authentication Verbose: 0 : Received request: GET https://[myService].azurewebsites.net/api/[myResource]
Microsoft.Azure.AppService.Authentication Warning: 0 : JWT validation failed: IDX10214: Audience validation failed. Audiences: 'https://[myService].azurewebsites.net/'. Did not match:  validationParameters.ValidAudience: '[AAD ClientId]' or validationParameters.ValidAudiences: 'http://[myService].azurewebsites.net'.
Microsoft.Azure.AppService.Authentication Information: 0 : Sending response: 401.71 Unauthorized
The thread 0x3b00 has exited with code 0 (0x0).

问题似乎在于,请求的受众是 https,但 validParameters.ValidAudiences 集合仅包含 http.

What appears to be the issue is that the Audience presented with the request is https but the validParameters.ValidAudiences collection only contains http.

我看不到任何配置受众的方式,并且似乎在 Visual Studio 2015 创建应用服务时正在设置基于 http 的受众.有没有手动编辑 ValidAudience 集合的方法?

I can't see any way of configuring the Audience and it appears that the http based audience is being set when Visual Studio 2015 creates the App Service. Is there a way of manually editing the ValidAudience collection?

作为参考,我的客户端代码是:

For reference my client code is:

    private static void Main(string[] args)
    {
        string app_id_url = "https://[myService].azurewebsites.net/";
        string authority = "https://login.windows.net/[myDirectory].onmicrosoft.com/";
        string clientId = "[AAD ClientId]";
        string clientSecret = "[AAD Client Secret]";
        string apiBaseUrl = "https://[myService].azurewebsites.net/";

        string aadToken = GetTokenForApplication(authority, clientId, clientSecret, app_id_url);

        var apiClient = new HttpClient { BaseAddress = new Uri(apiBaseUrl) };
        apiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", aadToken);
        var apiResponse = apiClient.GetAsync(apiBaseUrl + @"api/[myResource]").Result;
        string apiResponseContent = apiResponse.Content.ReadAsStringAsync().Result;
        Console.WriteLine(apiResponseContent);
    }

    public static string GetTokenForApplication(string authority, string clientId, string clientSecret, string resourceUrl)
    {
        AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);
        ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
        AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resourceUrl, clientCred);
        string token = authenticationResult.AccessToken;
        return token;
    }

推荐答案

您的问题与有效受众有关.您可能有 2 个选择:

Your problem have something to do with the valid audiences. You may have 2 choices:

选项 1. 尝试使用 WebAPI 客户端 ID 作为 AcquireToken 方法的资源"参数而不是其 Uri 获取令牌.

Option 1. Try to acquire the token with the WebAPI client ID as the AcquireToken method 'resource' parameter, instead of its Uri.

选项 2.如果以前的方法不起作用,您应该使用 Azure 资源资源管理器.导航到您的 Web API,在 config 节点下找到 authSettings JSON 文档,并修改(在更改为读/写模式后)数组 allowedAudiences以满足您的需求.在您的情况下,您可能需要将 http 更改为 https

Option 2. If the previous method didn't work, you should have to modify the authentication settings of the App Service API, using Azure Resources Explorer. Navigate to your web API, find the authSettings JSON document under the config node, and modify (after having changed to Read/Write mode) the array allowedAudiences to match your needs. In your case you may have to change http to https

这篇关于使用 AAD 对 Azure API 应用程序进行身份验证时出现 401 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)