Why do I get sporadic invalid tokens for checking email in Identity ASP.NET?

I’m trying to understand why my users receive frequent invalid tokens when confirming their email. I can not reproduce the problem.

Here's the setting:

userManager.UserTokenProvider = new EmailTokenProvider<User>(); 

Here's how the token is generated:

 var code = await userManager.GenerateEmailConfirmationTokenAsync(user.Id); 

Here it is checked:

 var result = await userManager.ConfirmEmailAsync(user.Id, code); 

I understand that EmailTokenProvider uses a security stamp for invalidity. My understanding is that this brand is changed only when significant changes to the user object are made as a change in password or username. However, I often get invalid tokens so this is the only explanation.

I am looking for any signpost that will help me shed light on why this is happening.

Edit:

I dug up the source code (the documentation is very poor), and as @trailmax pointed out below EmailTokenProvider wrong for this use, business. It is based on TotpSecurityStampBasedTokenProvider , which has a hard-coded timeout on tokens up to 3 minutes!

+5
source share
1 answer

EmailTokenProvider generates a very short-lived token and looks like 6 digits. This token is intended for 2FA and is valid only for a short period of time (something like 10-15 minutes, does not know the actual value).

The best thing you can do is use the DataProtectorTokenProvider provided by Identity, and it's a little complicated because it is not easy to tear it from the hands of OWIN.

The way I get around this is to assign a static variable in my Start.Auth.cs , and then reuse it in the UserManager:

 public class AuthConfig { public static IDataProtectionProvider DataProtectionProvider { get; set; } public void Configuration(IAppBuilder app) { ConfigureAuth(app); } public void ConfigureAuth(IAppBuilder app) { DataProtectionProvider = app.GetDataProtectionProvider(); // do other configuration } } 

And then re-assign it in the UserManager constructor:

  var dataProtectorProvider = AuthConfig.DataProtectionProvider; var dataProtector = dataProtectorProvider.Create("My Asp.Net Identity"); this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, Guid>(dataProtector) { TokenLifespan = TimeSpan.FromHours(24), }; 

This way you get a very long email token, which lasts 24 hours.

I made the same mistake as you, but I had to fix it pretty soon, as users complained.

+8
source

Source: https://habr.com/ru/post/1208609/


All Articles