Asp.net 2.0身份,ConfirmEmailAsync()获取无效令牌

时间:2015-05-07 11:52:26

标签: asp.net asp.net-identity owin

我尝试使用Asp.net Identity 2.0确认用户的电子邮件。正如几篇博客所建议的那样,我将machineKey放在Web.Config文件中,以便加密和解密在Azure网站上运行。在本地我无法生成令牌。在尝试使用UserManager.ConfirmEmailAsync方法确认(由我的web api生成的令牌)时,我收到“无效令牌”。我尝试过UrlEncoding我的代码,但那没用。我找不到足够的帮助来解决这个问题。

电子邮件生成代码如下所示

Inhalt00001

确认电子邮件地址

  code = HttpUtility.UrlEncode(UserManager.GenerateEmailConfirmationToken(identityUser.Id));
 _logger.Info("Generate confiruation token: " + code);

 string link = model.ConfirmUrl + string.Format("?userId={0}&code={1}", HttpUtility.UrlEncode(identityUser.Id), code);
 Configuration.Services.GetTraceWriter().Info(Request, Category, "Account GenereatedLink: " + link);

 UserManager.SendEmail(identityUser.Id, "Contactbook confirmation", link);

Startup.auth.cs代码

       IdentityResult idResult = await UserManager.ConfirmEmailAsync(userId, code);
        IHttpActionResult result = GetErrorResult(idResult);

AuthorizationManager.cs

app.CreatePerOwinContext(CBIndentityDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = true
        };
        app.UseOAuthBearerTokens(OAuthOptions);

的Web.config

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var appDbContext = context.Get<CBIndentityDbContext>();
        var appUserManager = new ApplicationUserManager(new UserStore<IdentityUser>(appDbContext));

        // Configure validation logic for usernames
        appUserManager.UserValidator = new UserValidator<IdentityUser>(appUserManager)
        {
            AllowOnlyAlphanumericUserNames = true,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        appUserManager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 7,
            RequireDigit = false
        };

        appUserManager.EmailService = new ContactbookEmailService();

        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            appUserManager.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser>(dataProtectionProvider.Create("ASP.NET Identity"))
            {
                //Code for email confirmation and reset password life time
                TokenLifespan = TimeSpan.FromHours(6)
            };
        }

        return appUserManager;
    }

当我删除machineKey时,每件事都运行正常。我需要有machinKey,以便EmailConfirmation在Azure中正常工作。

提前致谢。

2 个答案:

答案 0 :(得分:0)

有时当令牌具有“+”字符时,它会在返回到您的服务器时转换为“”,这可能是无效的原因。我用下面的方法来解决这个问题。

    private string SanitizeToken(string token)
    {
        return token.Trim().Replace(" ", "+");
    }

您可以在here.

查看完整的实施情况

答案 1 :(得分:0)

在发送之前对“代码”应用编码,并使用解码作为确认“代码”。

 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);
    }
}

实施例: - 发送前:UrlEncoding.Base64ForUrlEncode(code) 确认后:UrlEncoding.Base64ForUrlDecode(code)