aspnet identity invalid token on confirmation emai

2019-01-09 03:43发布

I'm trying to confirm an account but I'm getting "invalid token." error.

Here's what I'm trying:

var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmacaoEmail", "Usuario", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

await UserManager.SendEmailAsync(user.Id, "Ativação de Conta", user.GetEmailAtivacao(model.Nome, callbackUrl));

if I call UserManager.ConfirmEmailAsync after this code, I can confirm the account. However, if I open the link that it's inside the variable callbackUrl and try to confirm through that action, I'm getting the error.

I thought it could be something with OwinContext, so I've decided to call HttpContext.GetOwinContext().GetUserManager<MyCustomUserService> but I'm getting the same error.

Any clues?

4条回答
男人必须洒脱
2楼-- · 2019-01-09 03:58

Most likely that the code in transit is modified by browser. Try doing UrlEncode on the token:

var code = await userManager.GenerateEmailConfirmationTokenAsync(userId);
code = System.Web.HttpUtility.UrlEncode(code);

Otherwise browser messes with the special symbols that can be present in the token.

查看更多
叼着烟拽天下
3楼-- · 2019-01-09 04:00

Ok, this wasted hours - no, days - of my life. After trying all other suggestions in this thread an in Asp.NET - Identity 2 - Invalid Token Error I found that instead of calling

await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

in the Register-method just before the GenerateEmailConfirmationTokenAsync-block

await SignInAsync(user, isPersistent: false);

was called which is defined as

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
}

I think this was caused by scaffolding the application with an older ASP.Net MVC Version. The described method can be found in http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity from 2013.

查看更多
迷人小祖宗
4楼-- · 2019-01-09 04:05

Serdar's solution was the key to the solution for empty spaces and + simbols using Angular as client web application.

But sometimes I was getting random "invalid token" error messages. AFter some queries to the user's database I've found that those errors were only with those users having spaces o dashes in their UserName.

Solution was configure the User Manager to allow those characters in UserNames. Meant to say that my user database was migrated from Druppal directly to SQL Server and many of those users avoided the default policy from UserValidator at User Manager.

You can find how-to configure the UserValidator to allow non-alphanumeric characters at the end of this thread:

Asp.NET - Identity 2 - Invalid Token Error

查看更多
Melony?
5楼-- · 2019-01-09 04:08

I have experienced the same problem. I solved the problem with the following code.

Sample:

var emailToken = _customManager.GenerateEmailConfirmationToken(userId);
emailToken = emailToken.Base64ForUrlEncode();

Extension Methods => Name Space : System.Text,System.Web

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);
        }
}
查看更多
登录 后发表回答