Extend the 2FA token expiration in ASP.NET Core

Shaunavon Blackmore 21 Reputation points
2022-05-09T16:46:18.733+00:00

Is there a way to extend the 2FA token expiration timespan with email in ASP.NET core?

I am using the Microsoft.AspNetCore.Identity and Microsoft.AspNetCore.Authentication classes to use the 2FA with Email. The token being sent via email sometimes is delayed getting to the user's email Inbox after 8 minutes so I want to increase the timeout expiration for the 2FA code to 10 minutes or more. I've set the ExpireTimeSpan to TimeSpan.FromMinutes(10) in the services.PostConfigure<CookieAuthentionOptions> in my ConfigureServices method in the Startup class but the 2FA code always expires after 6 minutes. This solution does not work.

Is there any option to increase this token expiration?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,397 questions
0 comments No comments
{count} votes

Accepted answer
  1. Brando Zhang-MSFT 3,446 Reputation points Microsoft Vendor
    2022-05-10T03:33:06.743+00:00

    According to the sources codes, you could find the usermanager.GenerateEmailConfirmationTokenAsync method will use the EmailToken provider to generate the token.

    The EmailToken provider's default value should be the token provider which you have used when you register the identity in startup.cs.

    So if you want to modify the token life time, you should modify the token provider's token lifespan property.

    For example, you could modify the token provider like below:

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

    Then you could modify the identity token provider like below:

    Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>().AddTokenProvider<DataProtectorTokenProvider<IdentityUser>>(TokenOptions.DefaultEmailProvider); 
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Shaunavon Blackmore 21 Reputation points
    2022-05-10T12:16:06.577+00:00

    Thank you @Brando Zhang-MSFT . This is exactly what I needed. Works like charm.

    0 comments No comments