我正在将Asp Net .Net Framekwork迁移到Asp Net Core 3。 为了重置密码,我使用了:
var provider = new DpapiDataProtectionProvider("Sample");
UserManager.UserTokenProvider = new DataProtectorTokenProvider<MyUser, int>(
provider.Create("EmailConfirmation"));
DpapiDataProtectionProvider 在新环境中不可用。我可以使用哪些替代方案?
首先,您需要创建自定义数据保护提供程序,例如
public class CustomEmailConfirmationTokenProvider<TUser> :
DataProtectorTokenProvider<TUser> where TUser : class
{
public CustomEmailConfirmationTokenProvider(
IDataProtectionProvider dataProtectionProvider,
IOptions<EmailConfirmationTokenProviderOptions> options,
ILogger<DataProtectorTokenProvider<TUser>> logger) : base(dataProtectionProvider, options, logger)
{
}
}
public class EmailConfirmationTokenProviderOptions :
DataProtectionTokenProviderOptions
{
public EmailConfirmationTokenProviderOptions()
{
Name = "EmailConfirmationDataProtectorTokenProvider";
TokenLifespan = TimeSpan.FromDays(7);
}
}
public class CustomPasswordResetTokenProvider<TUser> :
DataProtectorTokenProvider<TUser> where TUser : class
{
public CustomPasswordResetTokenProvider(
IDataProtectionProvider dataProtectionProvider,
IOptions<PasswordResetTokenProviderOptions> options,
ILogger<DataProtectorTokenProvider<TUser>> logger) : base(dataProtectionProvider, options, logger)
{
}
}
public class PasswordResetTokenProviderOptions : DataProtectionTokenProviderOptions
{
public PasswordResetTokenProviderOptions()
{
Name = "PasswordResetDataProtectorTokenProvider";
TokenLifespan = TimeSpan.FromDays(1);
}
}
启动.cs
services.AddIdentityCore<ApplicationUser>(options => {
options.Password.RequireDigit = true;
options.Password.RequiredLength = 6;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.Tokens.ProviderMap.Add("CustomEmailConfirmation", new TokenProviderDescriptor(typeof(CustomEmailConfirmationTokenProvider<ApplicationUser>)));
options.Tokens.EmailConfirmationTokenProvider = "CustomEmailConfirmation";
options.Tokens.ProviderMap.Add("CustomPasswordReset", new TokenProviderDescriptor(typeof(CustomPasswordResetTokenProvider<ApplicationUser>)));
options.Tokens.PasswordResetTokenProvider = "CustomPasswordReset";
options.SignIn.RequireConfirmedEmail = true; })
.AddRoles<ApplicationRole>()
services.AddTransient(o =>
{
var service = new CustomEmailConfirmationTokenProvider<ApplicationUser>(
o.GetService<IDataProtectionProvider>(),
o.GetService<IOptions<EmailConfirmationTokenProviderOptions>>(),
o.GetService<ILogger<DataProtectorTokenProvider<ApplicationUser>>>());
return service;
});
services.AddTransient(o =>
{
var service = new CustomPasswordResetTokenProvider<ApplicationUser>(
o.GetService<IDataProtectionProvider>(),
o.GetService<IOptions<PasswordResetTokenProviderOptions>>(),
o.GetService<ILogger<DataProtectorTokenProvider<ApplicationUser>>>());
return service;
});