0

In my .Net Core 3.1 project, sometimes tokens are invalid as error says.

According to this thread : ASP.NET Core Identity invalid token on confirmation email

I am following the instructions so I have changed my SendConfirmationLink action as below:

var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
byte[] tokenGeneratedBytes = Encoding.UTF8.GetBytes(code);
var codeEncoded = WebEncoders.Base64UrlEncode(tokenGeneratedBytes);

var callbackURLRoute = Url.Action("RegisterStandartUser", "Account", new
                       {
                           userId = user.Id,
                           token = codeEncoded
                       });

var callbackURL = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}{callbackURLRoute}";

await _mailService.SendConfirmationMailToStandartUser(user, callbackURL);

After this mail successfully delivers to users, some of the users can confirm their account but some of them are getting this error message.

The error is Invalid Token on server side.

My RegisterUser action (the link redirects to) is below:

 var user = await _userManager.FindByEmailAsync(model.Email);
 if (user == null) { throw new Exception("Cannot find user!"); }

var codeDecodedBytes = WebEncoders.Base64UrlDecode(model.EmailToken);
var codeDecoded = Encoding.UTF8.GetString(codeDecodedBytes);

var emailConfirm = await _userManager.ConfirmEmailAsync(user, codeDecoded);

Why my application sometimes accepts and sometimes doesn't those tokens?

Please help me...

Burak
  • 467
  • 4
  • 16
  • 1
    The problem might be that the token is timing out because the users are waiting too long to respond. I believe the default timeout on the token is 30 minutes. – GlennSills Mar 02 '21 at 14:15
  • 1
    Very enlightening answer! I am gonna try this and I will share the results with you. – Burak Mar 02 '21 at 20:17
  • My comment was from experience. This happened to me when using the default password reset facilities provided in IdentityServer4, which is built around Microsoft.AspNetCore.Identity . – GlennSills Mar 03 '21 at 14:41

1 Answers1

0

you have to create link like this :

var confirmationLink = Url.Action("EmailConfirmation", "Account", new { email = user.Email, token = token }, Request.Scheme);