【问题标题】:Unauthorized response with Invalid Audience error for Azure AD + ASP.Net Core 2.1Azure AD + ASP.Net Core 2.1 的未经授权的响应和无效的受众错误
【发布时间】:2021-07-27 00:19:57
【问题描述】:

我使用带有 Azure AD 身份验证的 ASP.net Core 2.1 开发了一个 UI 和 Web API。两者都注册了 Azure 应用程序注册。我在 UI 中使用下面的代码。但我收到了未经授权的错误。

string AZURE_AD_INSTANE = "https://login.microsoftonline.com/";
string TENANT_ID = "<tenant GUID>";
string CLIENT_ID = "<Client GUID ofWeb API>";
string SECRET = "<Secret created for Web API under Certificates & secrets>";
string RESOURCE = "https://MyOrg.onmicrosoft.com/TestWebAPI"; //Application ID URI set in Expose an API
ClientCredential ClientCredential = new ClientCredential(CLIENT_ID, SECRET);
string authority = String.Format("{0}{1}", AZURE_AD_INSTANE, TENANT_ID);


AuthenticationContext authContext = new AuthenticationContext(authority);
string accessToken = authContext.AcquireTokenAsync(RESOURCE, ClientCredential).Result.AccessToken;

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44326/api/values/Get");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult();

string status = response.StatusCode.ToString();

StartUp.cs

public void ConfigureServices(IServiceCollection services)
{
      services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
                .AddAzureADBearer(options => Configuration.Bind("AzureAd", options)); 
       services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

我正在获取访问令牌。当我签入 jwt.io 时,它显示“签名已验证”。但是 API 调用给出了未经授权的响应状态代码。当我检查响应头时,它的信息为“{Bearer error="invalid_token", error_description="The Audience is invalid"}”

我该如何解决这个问题?

【问题讨论】:

  • 我需要你提供截图,去aad>你的应用>公开一个API来提供截图。
  • @Carl,我已经按照你的要求提供了截图。请检查并告诉我您的建议。
  • 在响应中,我收到的错误为“{Bearer error="invalid_token", error_description="The Audience is invalid"}” for response.Headers.WwwAuthenticate

标签: azure asp.net-core azure-active-directory asp.net-core-webapi bearer-token


【解决方案1】:

确保 https://MyOrg.onmicrosoft.com/TestWebAPI 在您的 WebAPI 中注册为有效受众:

.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidAudiences = new List<string> 
        {
            "https://MyOrg.onmicrosoft.com/TestWebAPI",
            "..."
        }
    }
};

【讨论】:

  • 我已经用启动类“ConfigureServices()”方法更新了我的帖子。它已经包含 AddAzureADBearer。如果我用您的“AddJwtBearer”代码替换它,我会收到内部服务器错误。我还需要做点别的吗?
  • @Kattesang AddJwtBearer 在内部由 AddAzureADBearer 调用。需要恢复并配置注册的IOptions.
猜你喜欢
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 2020-03-11
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多