更改密碼時從所有瀏覽器中註銷使用者
當使用者填寫詳細資訊並點擊
Reset Password按鈕時。呼叫以下控制器:public ActionResult ResetPassword(ResetPassword model) { ... return RedirectToAction("Logout"); }當使用者更改密碼時,他們會
Logged Out從瀏覽器中獲取。但是,如果他們同時登錄到另一個瀏覽器,他們仍然在另一個瀏覽器上登錄。我想在使用者更改密碼時從他們登錄的所有瀏覽器中註銷使用者。
所以我回到家,決定整理一些程式碼。給我看程式碼!!!
我會使用一個處理程序,所以驗證總是在使用者第一次訪問應用程序時完成,並且每次操作方法訪問都在一個地方完成。
這個想法是當使用者重置他們的密碼時,應用程序記錄使用者已經重置了他們的密碼並且沒有第一次登錄並註銷使用者。
user.HasResetPassword = true; user.IsFirstLoginAfterPasswordReset = false;當使用者登錄時,應用程序會驗證使用者之前是否重置了密碼並且現在是第一次登錄。如果這些聲明有效,則應用程序會更新其記錄,說明您尚未重置密碼並且您不是第一次登錄。
第1步
向 ApplicationUser 模型添加兩個屬性
第2步
在 Models 文件夾中添加一個類 AuthHandler.cs,實現如下。在此階段,您將驗證使用者是否已重置密碼,並且自密碼重置後首次未登錄。如果這是真的,將使用者重定向到登錄。
第 3 步
在 RouteConfig.cs 中呼叫 AuthHandler 以便為應用程序的每個傳入 http 請求呼叫它。
第四步
在 ResetPassword 方法中添加如下實現。在這一步,當使用者重置密碼時,更新屬性說,他們已經重置密碼並且沒有第一次登錄。請注意,使用者在重置密碼時也會顯式退出。
第 5 步
在 Login 方法中添加下面的實現。在這一步如果使用者登錄成功,驗證他們的密碼被重置並且他們第一次登錄是假的。如果所有條件都為真,則更新數據庫中的屬性,以便這些屬性處於準備好使用者將來重置密碼時的狀態。如此循環確定和更新密碼重置的狀態和重置密碼後的首次登錄。
最後
您的 AspnetUsers 表應如下所示
註釋
這就是我將如何處理它。我沒有測試過它,所以如果你遇到異常,你可能會修改它。它也都是硬編碼的,以顯示解決問題的方法。
我看到您正在使用 ASP.NET Identity 2。您正在嘗試做的事情已經內置。您需要做的就是更改SecurityStamp並且所有以前的身份驗證 cookie 都不再有效。
更改密碼後,您還需要更改SecurityStamp:
await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); await UserManager.UpdateSecurityStampAsync(User.Identity.GetUserId());如果您希望使用者保持登錄狀態,則必須重新發出新的身份驗證 cookie(登錄):
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);否則,啟動密碼更改的使用者/會話也將被註銷。
要立即註銷所有其他會話,您需要降低配置中的檢查間隔:
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromSeconds(1), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } });重現步驟:
- 在 VS2015 中創建了一個新的 Asp.Net Web App。
- 選擇 MVC 模板。
- 編輯App_Stat/Startup.Auth.cs,第 34 行:更改
validateInterval: TimeSpan.FromMinutes(30)為validateInterval: TimeSpan.FromSeconds(1)- 編輯Controllers/ManageController.cs,第 236 行:添加
UserManager.UpdateSecurityStampAsync方法呼叫。- 執行項目,創建使用者,登錄,打開不同的瀏覽器並登錄。
- 更改密碼,在其他瀏覽器中刷新頁面:您應該退出。






