Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `UserManager.ConfirmEmailAsync` throw for an invalid user?

Given my code in ConfirmEmail:

var result = await UserManager.ConfirmEmailAsync(userId, code);
if (result.Succeeded)
{
    model.Message = "Thank you for confirming your email.";
    model.IsConfirmed = true;
    return View(model);
}

based closely on the code from the standard MVC 5 project template, I would expect an invalid user to cause result.Succeeded == false, not to have ConfirmEmailAsync throw an InvalidOperationException.

like image 539
ProfK Avatar asked Oct 04 '15 16:10

ProfK


1 Answers

The source code of UserManager.ConfirmEmailAsync is:

public virtual async Task<IdentityResult> ConfirmEmailAsync(TKey userId, string token)
{
    ThrowIfDisposed();
    var store = GetEmailStore();
    var user = await FindByIdAsync(userId).ConfigureAwait(false);
    if (user == null)
    {
        throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound, userId));
    }
    if (!await VerifyUserTokenAsync(userId, "Confirmation", token))
    {
        return IdentityResult.Failed(Resources.InvalidToken);
    }
    await store.SetEmailConfirmedAsync(user, true).ConfigureAwait(false);
    return await UpdateAsync(user).ConfigureAwait(false);
}

You can see that InvalidOperationException is thrown when user was not found using FindByIdAsync(userId).

So this behaviour is by design.

like image 176
xZ6a33YaYEfmv Avatar answered Oct 05 '22 22:10

xZ6a33YaYEfmv