ASP NET 5 - 使用身份时忽略自定义身份验证方案处理程序

ASP NET 5 - Custom Authentication scheme handler is ignored when using Identity

忽略自定义身份验证方案和处理程序。 当控制器方法被 [Authorize] 注释时,我的方案没有受到挑战,即使它被设置为默认身份验证方案。相反,302 状态发送并重定向到 /Accounts/Login...。 不仅这个 URL 甚至不存在于我的应用程序中(我在客户端使用 Blazor WASM),而且我的应用程序中根本没有代码应该造成这种行为。 当我直接在属性中指定它时,将调用我的身份验证处理程序:[Authorize(AuthenticationScheme = CustomAuthHandler.SchemeName)]

为什么默认身份验证方案被忽略,而是 运行 代码中根本没有指定的内容? 如果 AddIdentity() 配置了这种意外行为,它在哪里记录以及如何重新配置​​? 如何让框架不忽略我注册为默认的处理程序?

一切正常,直到我切换到 .NET 5 并开始使用身份框架。

这是我的 ConfigureServices:

services.AddDbContext<ApplicationDbContext>(options =>
        {
            options.UseMySql(Configuration.GetConnectionString("DefaultConnection"), ServerVersion.FromString("10.5.6-mariadb"));
        });

services.AddIdentity<ApplicationUser, IdentityRole>(
        options =>
            {
                options.User.RequireUniqueEmail = true;
            }    
        )
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddClaimsPrincipalFactory<ApplicationUserClaimsFactory>();

services.AddControllersWithViews();
services.AddRazorPages();

services.AddAuthentication(
     options =>
     {
         options.DefaultScheme = CustomAuthHandler.SchemeName;
     }
)
.AddScheme<AuthenticationSchemeOptions, CustomAuthHandler>(CustomAuthHandler.SchemeName, x => {  });

好的,AddIdentity()方法确实导致了问题。 解决方案是用 AddIdentityCore() 替换它,这是一种更轻量级的方法,并且在后台做的事情更少。然后必须手动添加缺少的服务,例如AddRoles(),如文档中所述。