我正在尝试确认帐户,但我收到“无效令牌”。错误。
以下是我正在尝试的内容:
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));
如果我在此代码后拨打UserManager.ConfirmEmailAsync
,我可以确认该帐户。但是,如果我打开它在变量callbackUrl中的链接并尝试通过该操作进行确认,我就会收到错误。
我认为它可能是OwinContext的东西,所以我决定打电话给HttpContext.GetOwinContext().GetUserManager<MyCustomUserService>
,但我得到同样的错误。
任何线索?
答案 0 :(得分:24)
传输中的代码很可能是由浏览器修改的。尝试在令牌上执行UrlEncode:
var code = await userManager.GenerateEmailConfirmationTokenAsync(userId);
code = System.Web.HttpUtility.UrlEncode(code);
否则浏览器会混淆令牌中可能出现的特殊符号。
答案 1 :(得分:22)
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);
}
}
答案 2 :(得分:2)
Serdar的解决方案是使用Angular作为客户端Web应用程序解决空白空间和+ simbols的关键。
但有时我会收到随机的“无效令牌”错误消息。在对用户数据库的一些查询后,我发现这些错误只发生在用户名中有空格或短划线的那些用户。
解决方案是将用户管理器配置为允许UserNames中的这些字符。可以说我的用户数据库已直接从Druppal迁移到SQL Server,其中许多用户在User Manager上避免使用UserValidator的默认策略。
您可以找到如何配置UserValidator以在此线程的末尾允许使用非字母数字字符:
答案 3 :(得分:2)
好的,这浪费了我生命中的几个小时 - 不,几天。在尝试了这个帖子中的所有其他建议后,在Asp.NET - Identity 2 - Invalid Token Error我发现不是调用
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
在GenerateEmailConfirmationTokenAsync-block 之前的Register-method中的
await SignInAsync(user, isPersistent: false);
被调用,定义为
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
}
我认为这是因为使用较旧的ASP.Net MVC版本搭建应用程序引起的。所描述的方法可以在2013年的http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity中找到。
答案 4 :(得分:0)
万一这些解决方案对您不起作用-我在Asp.Net Core项目中遇到了问题,因为我在Startup.cs中添加了以下配置:
services.Configure<RouteOptions>(options =>
{
options.LowercaseUrls = true;
options.LowercaseQueryStrings = true;
});
第二个设置导致确认代码转换为小写,从而导致验证失败。理想情况下,我想保持查询字符串参数的小写字母不变,而不更改查询字符串的值,但是我没有找到一种方法,所以我删除了查询字符串设置:
services.Configure<RouteOptions>(options =>
{
options.LowercaseUrls = true;
});