Scott L
Scott L

Reputation: 667

ASP Identity Core GeneratePasswordResetTokenAsync expired

I have set up an Identity Server 4 project in .NET Core 2.1, I have everything working but when I use the user manager to generate the reset password token, the token expires after 24 hours, can I change this so it's 48 hours?

My code to send the reset token looks like this:

var code = await _userManager.GeneratePasswordResetTokenAsync(user);

var callbackUrl = url.EmailConfirmationLink(user.Id, code, scheme);

My ConfigureServices looks like this:

   services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {
            config.SignIn.RequireConfirmedEmail = true;
        })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

Thanks :)

Upvotes: 18

Views: 19696

Answers (1)

Charmis Varghese
Charmis Varghese

Reputation: 595

Adding the following code to ConfigureServices() method in Startup.cs class should help you.

services.Configure<DataProtectionTokenProviderOptions>(options =>
    options.TokenLifespan = TimeSpan.FromDays(2));

Default Token Lifespan is 24 hours (1 day). Please refer github and TokenOptions

This will modify the lifespan for all tokens (email confirmation, but also password reset tokens for example). To only modify the email confirmation tokens, it's a little more work, but nothing too much.

Create a custom token provider and its options:

public class CustomEmailConfirmationTokenProvider<TUser>
    : DataProtectorTokenProvider<TUser> where TUser : class
{
    public CustomEmailConfirmationTokenProvider(IDataProtectionProvider dataProtectionProvider,
        IOptions<CustomEmailConfirmationTokenProviderOptions> options,
        ILogger<DataProtectorTokenProvider<TUser>> logger) : base(dataProtectionProvider, options, logger)
    {
    }
}

public class CustomEmailConfirmationTokenProviderOptions : DataProtectionTokenProviderOptions
{
}

Then add and configure it in Program.cs (your exact code may vary, but you must add the three marked lines):

builder.Services.AddDefaultIdentity<ApplicationUser>(options =>
{
    options.SignIn.RequireConfirmedAccount = true;
    options.Tokens.EmailConfirmationTokenProvider = "CustomEmailConfirmationTokenProvider"; // Add this
})
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddTokenProvider<CustomEmailConfirmationTokenProvider<IdentityUser>>("CustomEmailConfirmationTokenProvider"); // Add this

builder.Services.Configure<CustomEmailConfirmationTokenProviderOptions>(o =>
    o.TokenLifespan = TimeSpan.FromDays(2)); // Add this

Upvotes: 37

Related Questions