Asp.net
身份框架測試確認電子郵件令牌是否過期
是否可以使用身份框架測試確認電子郵件令牌是否過期
UserManager?無論錯誤是什麼,從以下:var result = await UserManager.ConfirmEmailAsync(userId, code);我收到一個通用的“無效令牌”錯誤。
我找到了一種方法來解析發行日期的令牌,然後您可以檢查它是否在允許的時間跨度內(如果未指定,則預設為 24 小時)。
身份.cs
應用使用者管理器
public IDataProtector Protector { get; set; } public TimeSpan TokenLifespan { get; set; }應用程序使用者管理器創建()
// 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 的早期版本在這裡)。此外,如果它以糟糕的形式回答您自己提出的問題,我深表歉意,但我忍不住繼續尋找更好的解決方案。