添加自定义令牌配置 CustomEmailConfirmationTokenProviderOptions:
/// <summary>
/// 自定义的令牌配置类
/// </summary>
public class CustomEmailConfirmationTokenProviderOptions : DataProtectionTokenProviderOptions { }
添加自定义令牌 CustomEmailConfirmationTokenProvider:
/// <summary>
/// 自定义邮件验证令牌提供程序
/// </summary>
/// <typeparam name="TUser"></typeparam>
public class CustomEmailConfirmationTokenProvider<TUser> : DataProtectorTokenProvider<TUser> where TUser : class
{
public CustomEmailConfirmationTokenProvider(IDataProtectionProvider dataProtectionProvider,
IOptions<CustomEmailConfirmationTokenProviderOptions> options) : base(dataProtectionProvider, options)
{
}
}
在 Startup 中配置自定义令牌的过期时间:
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<IdentityOptions>(options =>
{
options.Password.RequiredLength = 6;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.SignIn.RequireConfirmedEmail = true;
// 通过自定义的CustomEmailConfirmation名称来覆盖旧有token名称,
// 是它与AddTokenProvider<CustomEmailConfirmationTokenProvider<ApplicationUser>>("ltmEmailConfirmation")
// 关联在一起
options.Tokens.EmailConfirmationTokenProvider = "ItmEmailConfirmation";
});
// Token 有效期修改为 10h
services.Configure<DataProtectionTokenProviderOptions>(
opt => opt.TokenLifespan = TimeSpan.FromHours(10));
// 仅更改电子邮件验证令牌类型的有效时间为 10s
services.Configure<CustomEmailConfirmationTokenProviderOptions>(
opt => opt.TokenLifespan = TimeSpan.FromMilliseconds(10));
...
// 1.添加 Identity 服务 2.使用 AppDbContext 存储与身份认证相关的数据
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddErrorDescriber<CustomIdentityErrorDescriptor>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders()
.AddTokenProvider<CustomEmailConfirmationTokenProvider<ApplicationUser>>("ItmEmailConfirmation");
...
}