由于身份用戶密碼存在散列差異,我們需要保留舊用戶而不強制他們更新密碼。所以我必須將散列更改為舊樣式。我正在關注這個答案https://stackoverflow.com/a/57074910/1651298但是盡管PasswordHasher在服務容器中被替換了,但新的哈希器沒有被使用。
重現問題的步驟:
為認證創建ASP Core MVC專案.NET 6并選擇Individual Accounts認證。更改Program.cs檔案:
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Proofs.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
var serviceDescriptor = builder.Services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(IPasswordHasher<IdentityUser>));
builder.Services.Remove(serviceDescriptor);
builder.Services.AddScoped<IPasswordHasher<IdentityUser>, OldMvcPasswordHasher>();
//builder.Services.Replace(new ServiceDescriptor(
// serviceType: typeof(IPasswordHasher<IdentityUser>),
// implementationType: typeof(OldMvcPasswordHasher),
// ServiceLifetime.Scoped));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
public class OldMvcPasswordHasher : PasswordHasher<IdentityUser>
{
public override PasswordVerificationResult VerifyHashedPassword(IdentityUser user, string hashedPassword, string providedPassword)
{
return PasswordVerificationResult.SuccessRehashNeeded;
}
}
我嘗試洗掉和添加新服務,也替換服務,但是VerifyHashedPassword當我嘗試登錄時沒有呼叫新方法。
uj5u.com熱心網友回復:
在我的一個專案中,我將現有用戶(使用我自己的自定義表)遷移到具有 .NET Core Identity 的 .NET 6 專案中。在 DataContext 中,我通過舊應用程式中的舊哈希列擴展了我的用戶表。
每當用戶嘗試登錄(使用電子郵件 密碼)時,我都會檢查舊哈希列中是否仍有值。如果是這樣的話,
- 我根據舊機制計算舊哈希,看看它們是否匹配
- 如果它們匹配,我使用 .NET Core Identity 設定新密碼(基于用戶輸入的內容。用戶不知道我更改了底層哈希演算法)。我通過創建 PasswordResetToken 然后使用 ResetPassword 功能來做到這一點。
- 之后,我從用戶行中洗掉了舊哈希。
在您的情況下,只需按照適用于新用戶的方式設定 .NET Core 身份。注意在登錄方法期間遷移現有密碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/457060.html
下一篇:Raven.Client.Exceptions.Database.DatabaseDoesNotExistException:'資料庫'*****'不存在
