ASP.NET 核心中的混合身份验证(Windows 和 AAD JwtBearer)

Mixed Authentication in ASP.NET Core (Windows and AAD JwtBearer)

我正在开发 .Net 5 Web 应用程序,它应该同时具有 Windows 和 Azure Active Directory JwtBearer 身份验证。一个控制器将使用一个 windows 身份验证,另一个身份验证将用于其他控制器。很清楚如何设置一个或另一个,但我不确定如何设置它们。

对于Windows身份验证:

services.AddAuthentication(IISDefaults.AuthenticationScheme);

对于 Azure Active Directory JwtBearer 身份验证:

services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
      .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

似乎无法在AddAuthentication 方法中设置多个身份验证,我想知道我们是否可以同时进行多个身份验证?我想在 Startup.cs 中以某种方式设置它们,并有一个带有身份验证方案的控制器属性。

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class JwtBearerProtectedController : ControllerBase
...
[Authorize(AuthenticationSchemes = IISDefaults.AuthenticationScheme)]
public class WindowsAuthProtectedController : ControllerBase

更新: 通过反复试验,我发现启动配置适用于 Windows 身份验证和 AAD 承载身份验证。

JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
IdentityModelEventSource.ShowPII = true;

services
   .AddAuthentication(IISDefaults.AuthenticationScheme)
   .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options))

是的,您绝对可以有多个身份验证选项

我想将您引导至此 msft 文档

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-5.0