houman_ag
houman_ag

Reputation: 237

Issue with Asp.net identity Email Confirmation Token: "Invalid Token"

I am using asp.net identity and have the following partial code in my Account/Register method:

string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

string codeHtmlVersion = HttpUtility.UrlEncode(code);

var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = codeHtmlVersion }, protocol: Request.Url.Scheme);

I then send the callbackUrl to the user in an email. When I debug the code, I see the following values:

code: "GE2HDQSSjAboLqEBdBv5rTjyksC09o110uqa4Dh+02TK4R+lhwgfjEaFiZkOc9GfQBKKryTTIgeITlgDgtvnDtVvk6SJyAjw7iuSPdNe+9tfUhcReAn50YqZp0aYbHy2QyHLc7EAUSyd/SJpCHdlgRsaAdOqpBPlI4zcd3FlbuMxiRdjHJq3q2K12YdQWcCF"

codeHtmlVersion: "GE2HDQSSjAboLqEBdBv5rTjyksC09o110uqa4Dh%2b02TK4R%2blhwgfjEaFiZkOc9GfQBKKryTTIgeITlgDgtvnDtVvk6SJyAjw7iuSPdNe%2b9tfUhcReAn50YqZp0aYbHy2QyHLc7EAUSyd%2fSJpCHdlgRsaAdOqpBPlI4zcd3FlbuMxiRdjHJq3q2K12YdQWcCF"

Then in my ConfirmEmail method, I reverse the values (or so I intend to):

public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
  string codeHtmlVersion = HttpUtility.UrlEncode(code);

  var result = await UserManager.ConfirmEmailAsync(userId, codeHtmlVersion);
  ....
}

When the user clicks on the confirmation link from his email, in my debug session, I see the following values:

code: "GE2HDQSSjAboLqEBdBv5rTjyksC09o110uqa4Dh%2b02TK4R%2blhwgfjEaFiZkOc9GfQBKKryTTIgeITlgDgtvnDtVvk6SJyAjw7iuSPdNe%2b9tfUhcReAn50YqZp0aYbHy2QyHLc7EAUSyd%2fSJpCHdlgRsaAdOqpBPlI4zcd3FlbuMxiRdjHJq3q2K12YdQWcCF"

codeHtmlVersion: "GE2HDQSSjAboLqEBdBv5rTjyksC09o110uqa4Dh%252b02TK4R%252blhwgfjEaFiZkOc9GfQBKKryTTIgeITlgDgtvnDtVvk6SJyAjw7iuSPdNe%252b9tfUhcReAn50YqZp0aYbHy2QyHLc7EAUSyd%252fSJpCHdlgRsaAdOqpBPlI4zcd3FlbuMxiRdjHJq3q2K12YdQWcCF"

So as it can be seen my code is changing somehow and so the user receives the "Invalid Token" error message. Can someone help me figure out what I'm doing wrong here? Much appreciated.

Upvotes: 2

Views: 2605

Answers (2)

HassanBakri
HassanBakri

Reputation: 91

The below code worked for me:

 HttpUtility.HtmlDecode(code);

Upvotes: 0

jimSampica
jimSampica

Reputation: 12410

You are encoding a second time when you want to be decoding in ConfirmEmail

string codeHtmlVersion = HttpUtility.UrlDecode(code);

Analyzing how your token is getting changed:

  1. + becomes %2b after encoding for the first time
  2. %2b becomes %252b after encoding the second time (it encodes the % symbol to %25)

Upvotes: 4

Related Questions