【问题标题】:Asp.net 2.0 Identity, ConfirmEmailAsync() getting Invalid TokenAsp.net 2.0 身份,ConfirmEmailAsync() 获取无效令牌
【发布时间】:2015-07-17 23:30:36
【问题描述】:

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

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

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

确认电子邮件代码

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

Startup.auth.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);

AuthorizationManager.cs

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

Web.config

<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5.2" />
<machineKey decryptionKey="6F7DEAA44E5E06B6B7480B055FF39960D69AD32BCBB178EB" validationKey="17D85F8147CF02697D16B05726B9D68E473A3BF79EB79AE4E7EF8E84DA6CCC46BFFB975741DA4D1F37F0EF41651422A2745296BA953CE0370D4337E2900C2A18" validation="SHA1" decryption="Auto" />

删除 machineKey 后一切正常。我需要 machinKey 以便 EmailConfirmation 在 Azure 中正常工作。

提前致谢。

【问题讨论】:

  • 同样的问题,你解决了吗?

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


【解决方案1】:

有时当token有“+”字符时,当它返回到你的服务器时它会转换为“”,这可能是无效的原因。我为我使用了以下方法。

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

您可以在here.查看完整的实现

【讨论】:

    【解决方案2】:

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

     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)

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 2015-05-07
      • 1970-01-01
      • 2018-03-19
      • 2015-04-29
      • 2015-12-13
      • 2015-06-21
      • 2021-08-30
      • 2015-01-30
      相关资源
      最近更新 更多