如何让.NET5服务与MVC5 ASP.NET Identity用户数据库兼容共用
问题根因
你遇到的配置不生效问题核心有两个原因:
AddIdentity内部会默认注册IPasswordHasher实例,默认采用IdentityV3兼容模式,你通过services.Configure注册的配置如果时机不对,不会被默认的PasswordHasher实例读取- 你使用Autofac作为DI容器,若存在自动服务注册逻辑,会覆盖.NET Core默认DI容器中注册的
PasswordHasher配置,导致兼容性设置失效
解决步骤
步骤1:显式注册强制V2兼容的密码哈希器
将以下代码放在AddIdentity注册逻辑的后面,覆盖默认的IPasswordHasher注册:
services.AddScoped<IPasswordHasher<ApplicationUser>, PasswordHasher<ApplicationUser>>(sp => { return new PasswordHasher<ApplicationUser>(new OptionsWrapper<PasswordHasherOptions>( new PasswordHasherOptions { CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2 })); });
步骤2:适配Autofac DI注册规则
在Autofac的ConfigureContainer方法中显式注册密码哈希器,避免Autofac自动注册逻辑覆盖配置:
builder.RegisterType<PasswordHasher<ApplicationUser>>() .As<IPasswordHasher<ApplicationUser>>() .WithParameter("optionsAccessor", new OptionsWrapper<PasswordHasherOptions>( new PasswordHasherOptions { CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2 })) .InstancePerLifetimeScope();
可选:彻底禁用密码哈希自动升级逻辑
如果需要彻底避免新系统修改旧密码哈希,可自定义密码哈希器,拦截SuccessRehashNeeded返回结果,从根源禁止触发哈希升级写入:
public class NoUpgradePasswordHasher<TUser> : PasswordHasher<TUser> where TUser : class { public NoUpgradePasswordHasher(IOptions<PasswordHasherOptions> optionsAccessor) : base(optionsAccessor) { } public override PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword) { var result = base.VerifyHashedPassword(user, hashedPassword, providedPassword); // 将需要重哈希的结果直接标记为验证成功,不会触发数据库密码更新 return result == PasswordVerificationResult.SuccessRehashNeeded ? PasswordVerificationResult.Success : result; } }
注册时替换为自定义实现即可:
// 替换之前的PasswordHasher注册 services.AddScoped<IPasswordHasher<ApplicationUser>, NoUpgradePasswordHasher<ApplicationUser>>(sp => { return new NoUpgradePasswordHasher<ApplicationUser>(new OptionsWrapper<PasswordHasherOptions>( new PasswordHasherOptions { CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2 })); });
完成上述配置后,.NET5服务会完全采用Identity V2的哈希规则,不会修改数据库中已有的旧格式密码,两个系统可正常共用用户库。
内容的提问来源于stack exchange,提问作者R26
相关产品推荐
相关产品推荐

