1

I've seen this discussed a few times but I still can't solve it.

My registration process works well 99% of the time. But the occasional time I get an invalid token error when confirming an email address (via a link in an email). I'm even URL encoding/decoding the token now too, but I still get the occasional error.

Register action:

string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
code = System.Web.HttpUtility.UrlEncode(code);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

and Confirm action:

code = System.Web.HttpUtility.UrlDecode(code);
var result = await UserManager.ConfirmEmailAsync(userId, code);

I can confirm each 'failing' user does have a Security Stamp. And the name/username doesn't appear to contain any dodgy characters.

Is there anything else I can check?

adiga
  • 34,372
  • 9
  • 61
  • 83
Captain_Planet
  • 1,228
  • 1
  • 12
  • 28
  • Do you have `MachineKey` in your web.config? – trailmax Feb 15 '17 at 22:48
  • Hmmm no I don't. I'll work out how to add one and let you know how I get on. Because the issue is intermittent it may take me a while to tell if it worked or not. Thanks for the pointer. – Captain_Planet Feb 15 '17 at 23:14
  • 1
    Part of the token contains a name of the web-application (defined in IIS) and if you run it in the cloud, after app restart you might get a different name - this can also cause your issue. But machine key _should_ fix it. Just to confirm - get a token, restart your IIS, try confirming the token, then do the same with machine key. – trailmax Feb 15 '17 at 23:19
  • I appreciate the response - will keep you updated! – Captain_Planet Feb 16 '17 at 08:14

1 Answers1

0

You can try this code.

var encodedCode= code.Base64ForUrlEncode();
var decodedCode= encodedCode.Base64ForUrlDecode();

public static class UrlEncoding
{
        public static string Base64ForUrlEncode(this string str)
        {
            byte[] encbuff = Encoding.UTF8.GetBytes(str);
            return HttpServerUtility.UrlTokenEncode(encbuff);
        }

        public static string Base64ForUrlDecode(this string str)
        {
            byte[] decbuff = HttpServerUtility.UrlTokenDecode(str);
            return Encoding.UTF8.GetString(decbuff);
        }
}