ASP.NET Core如何配置Windows与AAD JwtBearer混合认证
.NET 5 同时配置Windows认证与Azure AD JwtBearer认证方案
需求背景
开发.NET 5 Web应用时需要同时适配两种认证规则:
- 特定控制器使用Windows认证
- 其余控制器使用Azure Active Directory JwtBearer认证
单认证方案单独配置代码
Windows认证单独配置
services.AddAuthentication(IISDefaults.AuthenticationScheme);
Azure AD JwtBearer认证单独配置
services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme) .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
核心诉求
AddAuthentication方法无法直接设置多个默认认证方案,需要实现两种认证同时生效,支持在控制器层通过特性指定对应认证方案,预期用法示例如下:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class JwtBearerProtectedController : ControllerBase // 控制器实现逻辑 ... [Authorize(AuthenticationSchemes = IISDefaults.AuthenticationScheme)] public class WindowsAuthProtectedController : ControllerBase // 控制器实现逻辑
可行配置方案
经过实际调试验证,以下Startup配置可同时支持两种认证:
JwtSecurityTokenHandler.DefaultMapInboundClaims = false; IdentityModelEventSource.ShowPII = true; services .AddAuthentication(IISDefaults.AuthenticationScheme) .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options))
注:该配置中
AddAuthentication的参数仅为全局默认认证方案,额外注册的Azure AD Bearer认证方案依然可以通过[Authorize]特性显式指定使用。
内容的提问来源于stack exchange,提问作者Oblomingo
相关产品推荐
相关产品推荐

