简体   繁体   中英

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.

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)

以下代码对我有用:

 HttpUtility.HtmlDecode(code);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM