ASP.NET Core MVC身份验证报错:未配置Identity.Application登录处理器
解决 "No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Identity.Application" 异常
这个问题的核心是你的认证方案配置和IdentityCore默认使用的方案不匹配,SignInManager默认会使用Identity.Application(即IdentityConstants.ApplicationScheme)作为登录方案,但你的认证中间件没有正确配置对应的处理程序。
问题分析
你当前的配置里同时做了两件冲突的事:
- 调用
AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)并单独添加了Cookie认证方案 - 使用
AddIdentityCore并配置ConfigureApplicationCookie(这是专门为Identity服务的Cookie配置)
SignInManager是Identity体系的一部分,它默认依赖Identity.Application方案,但你的认证中间件没有把这个方案注册为有效的认证处理程序,所以抛出了找不到Handler的异常。
修复步骤
调整你的ConfigureServices方法,让认证配置和Identity的默认方案对齐,具体修改如下:
public void ConfigureServices(IServiceCollection services) { // 1. 先注册IdentityCore相关服务,合并所有Identity配置 services.AddIdentityCore<User>(options => { // 密码设置 options.Password.RequireDigit = true; options.Password.RequiredLength = 8; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = true; options.Password.RequireLowercase = false; options.Password.RequiredUniqueChars = 6; // 锁定设置 options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); options.Lockout.MaxFailedAccessAttempts = 10; options.Lockout.AllowedForNewUsers = true; // 用户设置 options.User.RequireUniqueEmail = true; }) .AddSignInManager<ApplicationSignInManger<User>>() .AddUserManager<ApplicationUserManager<User>>() .AddUserStore<ApplicationUserStore>() .AddDefaultTokenProviders(); // 2. 注册自定义SignInManager(如果AddSignInManager未自动注册的话) services.AddScoped<SignInManager<User>, ApplicationSignInManger<User>>(); // 3. 配置认证,明确指定默认方案为Identity.Application services.AddAuthentication(options => { options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme; options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme; options.DefaultSignInScheme = IdentityConstants.ApplicationScheme; }) // 4. 配置Identity专用的Cookie,无需单独调用AddCookie .ConfigureApplicationCookie(options => { options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromDays(7); // 注意:Cookie.Expiration已过时,用ExpireTimeSpan替代 options.LoginPath = "/Account/Login"; options.LogoutPath = "/Account/Logout"; options.AccessDeniedPath = "/Account/AccessDenied"; options.SlidingExpiration = true; }); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddMvc(); }
关键修改点说明
- 移除单独的
AddCookie调用:ConfigureApplicationCookie已经会自动为Identity.Application方案配置对应的Cookie认证处理程序,重复添加会导致冲突。 - 统一认证方案:将认证的默认方案全部设置为
IdentityConstants.ApplicationScheme,确保和SignInManager使用的方案一致。 - 合并Identity配置:把原来单独的
Configure<IdentityOptions>合并到AddIdentityCore的参数中,避免重复配置。
另外,请确保你的ApplicationSignInManger<User>正确继承了SignInManager<User>,并且构造函数注入了所有必要的依赖(比如IUserClaimsPrincipalFactory<User>、IHttpContextAccessor等)。
完成这些修改后,再调用PasswordSignInAsync就应该能正常执行,不会再抛出那个异常了。
内容的提问来源于stack exchange,提问作者Kirill Ilin
相关产品推荐
相关产品推荐

