Identity Framework测试确认电子邮件令牌是否已过期 [英] Identity Framework test if confirm email token is expired

查看:140
本文介绍了Identity Framework测试确认电子邮件令牌是否已过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Identity Framework的UserManager测试确认电子邮件令牌是否已过期?无论错误是什么,都来自以下内容:

Is it possible to test whether a confirm email token is expired using Identity Framework's UserManager? No matter what the error is, from the following:

var result = await UserManager.ConfirmEmailAsync(userId, code);

我收到一个通用的无效令牌"错误.

I get a generic "Invalid Token" error.

推荐答案

我找到了一种方法来解析发行日期的令牌,然后可以检查该令牌是否在允许的时间范围内(如果未指定,则默认为24小时) ).

I found a way to parse the token for the date issued, which you can then check to see if is within the allowed timespan (default of 24hours if not specified).

ApplicationUserManager

public IDataProtector Protector { get; set; }

public TimeSpan TokenLifespan { get; set; }

ApplicationUserManager Create()

// Explicitly set token expiration to 24 hours. 
manager.TokenLifespan = TimeSpan.FromHours(24);
var dataProtectionProvider = options.DataProtectionProvider;
manager.Protector = dataProtectionProvider.Create("ASP.NET Identity");

if (dataProtectionProvider != null)
{
    manager.UserTokenProvider =
        new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"))
        {
            TokenLifespan = manager.TokenLifespan
        };
}

AccountController.cs

public async Task<ActionResult> ConfirmEmail(string Code, string UserId)
{
// Try/catch, validation, etc.
var tokenExpired = false;
var unprotectedData = UserManager.Protector.Unprotect(Convert.FromBase64String(Code));
var ms = new MemoryStream(unprotectedData);
using (BinaryReader reader = new BinaryReader(ms))
{
    var creationTime = new DateTimeOffset(reader.ReadInt64(), TimeSpan.Zero);
    var expirationTime = creationTime + UserManager.TokenLifespan;
    if (expirationTime < DateTimeOffset.UtcNow)
    {
        tokenExpired = true;
    }
 }
 // Do something if token is expired, else continue with confirmation
}

我找到了此博客文章和Nkosi的答案非常有用,如果您想查看Identity源代码,Microsoft会提供此处(MVC5和更低版本的Identity的早期版本以及此处).另外,如果您回答的问题很不好意思,我想道歉,您自己却是悬赏金,但我忍不住继续寻找更好的解决方案.

I found this blog post and Nkosi's answer to be extremely helpful, and if you want to go through the Identity source code, Microsoft has it here (The previous versions of Identity for MVC5 and lower here). Also, I apologize if its in poor form to answer a question that you, yourself put a bounty on, but I couldn't help but continue looking for a better solution.

这篇关于Identity Framework测试确认电子邮件令牌是否已过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆