0

I am trying to send a confirmation email from my API. The mail is sent without problems.

When I load the url from MVC5, I have this error:

enter image description here

I tried:

Asp.NET Identity 2 giving "Invalid Token" error

http://www.gunaatita.com/Blog/Invalid-Token-Error-on-Email-Confirmation-in-Aspnet-Identity/1056 --> My api and my MVC are two projects hosted on two servers, for this reason I try using machineKey validationKey.

The code I use is below:

Web API

        if (!await db.Users.AnyAsync(c => c.Email == userRequest.Email)) return StatusCode(HttpStatusCode.NotFound);

        var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(userContext));
        userManager.UserTokenProvider = new TotpSecurityStampBasedTokenProvider<ApplicationUser, string>();

        var user = await userManager.FindByNameAsync(userRequest.Email);

        var userId = user.Id;
        var code = await userManager.GenerateEmailConfirmationTokenAsync(user.Id);

        var url = "MyUrl" + "/Account/ConfirmEmail?userId=" + userId + "&code=" + code;

MVC5

        if (userId == null || code == null)
        {
            return View("Error");
        }

        var result = await UserManager.ConfirmEmailAsync(userId, code);
        return View(result.Succeeded ? "ConfirmEmail" : "Error");
Ankit Kumar
  • 397
  • 2
  • 11
  • 21
Jorge MHT
  • 36
  • 6

2 Answers2

0

For the token confirmation to work, the token needs to be saved in the Users table AspNetUsers.

Web API

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

MVC5

var result = await UserManager.ConfirmEmailAsync(userId, code);         
switch (result.Succeeded)
{
    case true:
    // Your code
    case false:
    //
    default:
    //
}
Alfred Wallace
  • 1,741
  • 1
  • 14
  • 32
-1

I think it throws 'invalid token' because the code parameter is too complex for querystring (contains special characters). So it is not redirecting to the page properly. To solve this problem:

string val = HttpServerUtility.UrlTokenEncode(Encoding.ASCII.GetBytes(code));

You can change to 'code' parameter with this.

Aman B
  • 2,276
  • 1
  • 18
  • 26