Azure AD 限制整个 ASP.NET Core API

Posted

技术标签:

【中文标题】Azure AD 限制整个 ASP.NET Core API【英文标题】:Azure AD Restricts entire ASP.NET Core API 【发布时间】:2022-01-11 20:35:54 【问题描述】:

创建由 Azure AD 保护的 WASS Blazor ASP.net Core 托管的 .NET 6 应用程序。我遵循了本指南: https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/hosted-with-azure-active-directory?view=aspnetcore-6.0

我只想限制对控制器中几个端点的访问。我尝试在控制器中添加和删除以下注释:

//[Authorize]
[Route("api/wikipages")]
[ApiController]
//[RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]
[AllowAnonymous]
public class WikiPageController : ControllerBase

即使我进入Program.cs 类并评论app.UseAuthentication();app.UseAuthorization();,在尝试访问API 时仍会收到以下错误:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]

未处理的异常渲染组件:''

Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessTokenNotAvailableException: ''

在 Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler.SendAsync(HttpRequestMessage 请求,CancellationToken cancelToken) 在 Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage 请求,CancellationToken 取消令牌) 在 System.Net.Http.HttpClient.g__Core|83_0(HttpRequestMessage 请求,HttpCompletionOption 完成选项,CancellationTokenSource cts,布尔 disposeCts,CancellationTokenSource pendingRequestsCts,CancellationToken originalCancellationToken)......

【问题讨论】:

【参考方案1】:

这个问题有三个解决方案,你可以看看这篇文章,对你有用。

相关博客:

How to send HTTP requests to public API without access token on an authentication enabled Blazor Wasm App?

您需要添加HttpClient,如下所示。

public static async Task Main(string[] args)

    // Add a plain "HttpClient" with a name.
    builder.Services.AddHttpClient("BlazorWasmApp.AnonymousAPI", client => 
    client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);

    builder.Services.AddHttpClient("BlazorWasmApp.ServerAPI", ...)
      .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
    ...
);

在你的页面中,你可以像下面这样调用。

@* @inject HttpClient Http *@
@inject IHttpClientFactory HttpClientFactory
...
@code 
protected override async Task OnInitializedAsync()

    ...
    // Don't get a HttpClient from DI directly for accessing a public API.
    // RecentlyUpdates = await Http.GetFromJsonAsync<string[]>("RecentlyUpdates");

    // Instead, get a HttpCient from IHttpClientFactory service with name explicitly.
    var http = HttpClientFactory.CreateClient("BlazorWasmApp.AnonymousAPI");
    RecentlyUpdates = await http.GetFromJsonAsync<string[]>("RecentlyUpdates");

【讨论】:

【参考方案2】:

Azure AD 不支持匿名身份验证,以便您能够在 WebAPI 中使用 AllowAnonymous 属性。 参考:Azure AD allow anonymous

如果你想允许匿名请求,你可以使用OWIN组件来实现认证,而不是使用Easy Auth。

这是一个使用 OpenId 组件保护 MVC 的示例:

active-directory-dotnet-webapp-openidconnect

有关更多详细信息,请参阅此 SO 线程:

1) AllowAnonymous is not working with azure ad authentication

2) How to allow unauthenticated requests to a controller when rest of site is using Azure AD Authentication

【讨论】:

以上是关于Azure AD 限制整个 ASP.NET Core API的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core 2.2 中的 Azure AD 身份验证

ASP.NET Core 3.1 Azure AD 身份验证引发 OptionsValidationException

ASP.NET 5 API - Azure AD B2C

使用 Azure AD 的 Asp.net core mvc 基于角色的授权

如何在 ASP.NET Core 3 上同时使用 Azure AD 身份验证和身份?

ASP.NET Core Azure AD OpenID - 生产服务器上的令牌签名验证失败