You need to enable JavaScript to run this app. IdentityServer实现中已注册AddDefaultIdentity仍报IUserClaimsPrincipalFactory`1未注册异常
优惠活动
大模型
产品
解决方案
定价
更多

IdentityServer实现中已注册AddDefaultIdentity仍报IUserClaimsPrincipalFactory`1未注册异常

问题详情
  • 运行时抛出的异常信息:
System.InvalidOperationException: Service type: IUserClaimsPrincipalFactory`1 not registered.
  • 已实现的Identity服务注册代码:
services.AddDefaultIdentity<ApplicationUser>(options =>
            {
                //Disable account confirmation.
                options.SignIn.RequireConfirmedAccount = false;
                options.SignIn.RequireConfirmedEmail = false;
                options.SignIn.RequireConfirmedPhoneNumber = false;
            })
            .AddEntityFrameworkStores<ApplicationDbContext>();
  • 已实现的IdentityServer配置代码:
var builder = services.AddIdentityServer()
            .AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
            .AddInMemoryIdentityResources(IdentityServerConfig.IdentityResources)
            .AddInMemoryApiResources(IdentityServerConfig.ApiResources)
            .AddInMemoryClients(IdentityServerConfig.Clients)
            .AddAspNetIdentity<IdentityUser>();
错误根因

核心问题是用户实体泛型参数不匹配:AddDefaultIdentity 注册的是基于自定义ApplicationUser的全套Identity依赖服务,但后续AddAspNetIdentity传入的是ASP.NET Core Identity默认的IdentityUser泛型类型。DI容器会根据泛型参数区分不同的服务注册键,两个泛型类型不匹配就会导致找不到对应泛型的IUserClaimsPrincipalFactory<TUser>注册项。

修复方案
  • 统一全链路的用户实体泛型:将.AddAspNetIdentity<IdentityUser>()修改为.AddAspNetIdentity<ApplicationUser>(),确保IdentityServer依赖的用户实体类型和Identity服务注册的类型完全一致。
  • 调整服务注册顺序:优先完成AddDefaultIdentity的全量服务注册,再执行AddIdentityServer的相关扩展逻辑,避免后续服务注册流程覆盖原有Identity注册的依赖项。
  • 如果不需要AddDefaultIdentity自带的Razor登录页、外部登录集成等冗余组件,可以替换为.AddIdentityCore<ApplicationUser>()做轻量化集成,再按需补充密码策略、用户管理等所需配置,减少不必要的类型冲突。

内容的提问来源于stack exchange,提问作者Kishan Vaishnav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.24 20:24:06