尝试对 ASP.NET Core 3.1 使用多个身份验证方案时出现异常
Posted
技术标签:
【中文标题】尝试对 ASP.NET Core 3.1 使用多个身份验证方案时出现异常【英文标题】:Exceptions when trying to use multiple authentication schemes with ASP.NET Core 3.1 【发布时间】:2021-07-07 23:22:16 【问题描述】:我正在尝试使用 ASP.NET Core 3.1 添加多个身份验证方案,并在尝试向服务器发送不记名令牌时遇到此问题:
System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).
at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at NWebsec.AspNetCore.Middleware.Middleware.CspMiddleware.Invoke(HttpContext context)
at NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(HttpContext context)
at NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(HttpContext context)
at NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(HttpContext context)
at NWebsec.AspNetCore.Middleware.Middleware.MiddlewareBase.Invoke(HttpContext context)
以下是相关代码:
services.AddAuthentication(options =>
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
)
.AddJwtBearer("Custom", options =>
options.SaveToken = true;
options.RequireHttpsMetadata = true;
options.TokenValidationParameters = new TokenValidationParameters
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ValidateAudience = false,
ValidateIssuer = false
;
)
.AddJwtBearer("Keycloak", options =>
options.Authority = "http://localhost:8080/auth/realms/test";
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ValidateAudience = false,
ValidateIssuer = false
;
);
services.AddAuthorization(options =>
var authorizationPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, "Custom", "Keycloak")
.RequireAuthenticatedUser().Build();
options.AddPolicy("Bearer", authorizationPolicy);
);
任何人都能够看到我在这里做错了什么? 如果我只使用一个,这两种方案都可以单独工作。
【问题讨论】:
【参考方案1】:我找到了解决办法。
我需要添加
[Authorize(AuthenticationSchemes = "Custom, Keycloak")]
在我的基本控制器中。
【讨论】:
以上是关于尝试对 ASP.NET Core 3.1 使用多个身份验证方案时出现异常的主要内容,如果未能解决你的问题,请参考以下文章
ASP.NET Core 3.1 Azure AD 身份验证引发 OptionsValidationException
使用 KeyCloak 保护 ASP.NET Core 3.1 MVC 应用程序
阻止对 ASP.NET Core 3.1 API 的服务器到服务器或 Postman 调用
ASP.NET Core api 项目 3.1 在 IIS 上发布
Wcf 服务在 .NET Core 3.1 控制台应用程序中工作,但在 ASP.NET Core 3.1 Web API 中无法工作