ASP Net Core Identity令牌身份验证到期

时间:2018-08-27 04:18:29

标签: .net-core asp.net-core-2.0

我使用asp net core身份。这是我正在尝试做的事情,我不知道该怎么做,因此需要一些专家帮助。当新用户在我的应用程序中注册时,密码重置链接将发送到该人的电子邮件中。现在,当链接中的链接令牌已过期并且用户单击该链接时,我需要显示一条令牌已过期的消息。当用户单击电子邮件中的链接时,如何确定令牌是否已过期。有人可以建议实现此方案的方法吗?

1 个答案:

答案 0 :(得分:3)

ASP.NET Core具有内置的Claims系统,用于存储有关用户的信息。

为此,

  1. 添加辅助方法以将到期日期时间存储在Register.cshtml.cs中:

    private async Task AddTokenExpirationInfo(IdentityUser user, int span=1*24*60)
    {
        var expiresAt = DateTime.Now.Add(TimeSpan.FromMinutes(span));
        var tokenExpiredAtClaim = new Claim("ActivtationTokenExpiredAt", expiresAt.ToUniversalTime().Ticks.ToString());
        await _userManager.AddClaimAsync(user, tokenExpiredAtClaim);
    }
    
  2. 添加辅助方法,以检查令牌在ConfirmEmail.cshtml.cs中是否已过期:

    private async Task<bool> TokenExpiredValidate(IdentityUser user) {
        var claims = (await _userManager.GetClaimsAsync(user))
            .Where(c => c.Type == "ActivtationTokenExpiredAt");
        var expiredAt = claims.FirstOrDefault()?.Value;
        bool expired = true;    // default value
        if (expiredAt != null)
        {
            var expires = Convert.ToInt64(expiredAt);
            var now = DateTime.Now.Ticks;
            expired= now <= expires? false : true;
        }
        else {
            expired = false;
        }
        // clear claims
        await _userManager.RemoveClaimsAsync(user, claims);
        return expired;
    }
    
  3. 在有注册请求时调用AddTokenExpirationInfo

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        if (ModelState.IsValid)
        {
            var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
            var result = await _userManager.CreateAsync(user, Input.Password);
            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");
    
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                var callbackUrl = Url.Page(
                    "/Account/ConfirmEmail",
                    pageHandler: null,
                    values: new { userId = user.Id, code = code },
                    protocol: Request.Scheme);
    
                await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
    
                ///////////////// invoke here  ////////////////////
                AddTokenExpirationInfo(user);
    
                await _signInManager.SignInAsync(user, isPersistent: false);
                return LocalRedirect(returnUrl);
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }
    
        // If we got this far, something failed, redisplay form
        return Page();
    }
    
  4. 在您的TokenExpiredValidate中调用ConfirmEmail.cshtml.cs

    public async Task<IActionResult> OnGetAsync(string userId, string code)
    {
        if (userId == null || code == null)
        {
            return RedirectToPage("/Index");
        }
    
        var user = await _userManager.FindByIdAsync(userId);
        if (user == null)
        {
            return NotFound($"Unable to load user with ID '{userId}'.");
        }
        var result = await _userManager.ConfirmEmailAsync(user, code);
        if (!result.Succeeded)
        {
            throw new InvalidOperationException($"Error confirming email for user with ID '{userId}':");
        }
        if (await TokenExpiredValidate(user)) 
            throw new InvalidOperationException($"Token has alread expired '{userId}':");
    
        return Page();
    }
    

用户注册时,AspNetUserClaims表中将有一条记录:

Demo

当用户成功确认后,记录将被删除。提醒一下,一种更可靠的方法是使用后台服务清除过期记录。