0

Does anyone have an idea why this is happening to me?

In this case, 'result' is 'Success':

public async Task<IActionResult> TestConfirmInSameRequest(string userId)
{
    var user = await this._userManager.FindByIdAsync(userId);
    var code = await this._userManager.GenerateEmailConfirmationTokenAsync(user);
    var result = await this._userManager.ConfirmEmailAsync(user, code); 

    var newLocation = ...
    return Redirect(newLocation);
}

And in this case, 'result' always is 'InvalidToken' (even when I manually copy the original code and test with it)

public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
    var user = await this._userManager.FindByIdAsync(userId);
    var result = await this._userManager.ConfirmEmailAsync(user, code); 

    var newLocation = ...;
    return Redirect(newLocation);
}

protected async Task SendConfirmationEmail(string userId, bool originMobile)
{
    var user = await this._userManager.FindByIdAsync(userId);
    var code = await this._userManager.GenerateEmailConfirmationTokenAsync(user);

    var encodedCode = HttpUtility.UrlEncode(code);
    var callbackUrl = $"https://.../api/account/confirmemail?userId={userId}&code={encodedCode}";

    await this._userService.SendConfirmationEmailAsync(userId, callbackUrl);
}
Kalin Krastev
  • 552
  • 6
  • 19

1 Answers1

0

When sending (SendConfirmationEmail) the e-mail you urlencode the token, but in ConfirmEmail you are not decoding the token.

Encoding it just makes sure it can be used in a URL and no breaking characters are in the URL. However, the token you should validate is not the encoded one, its still the token you got before encoding. In other words; you need to decode the token again so its back to the way it was when it got generated.

RoelA
  • 581
  • 4
  • 15
  • The 'code' comes as already decoded. I have also tried decoding it using HttpUtility.UrlDecode(code). - Same result except that in this case when I compare the original generated code and the decoded, they look different as the decoded one is missing '+' symbols that were present before decoding and in the original one. – Kalin Krastev Mar 08 '19 at 14:18
  • Also as I've mentioned in the question, I tried copying the 'code' right after it was generated, and then pasting it in the 'ConfirmEmail' method directly, which also results in 'InvalidToken'. – Kalin Krastev Mar 08 '19 at 14:23