2017-05-05 87 views
0

我正在使用.Net MVC5身份和新的一般開發,所以忍受着我。如何強制用戶註銷鎖定在MVC5

如何顯示鎖定頁面並強制用戶根據鎖定狀態註銷?

爲了測試的目的,我做了兩個用戶,一個在角色「Admin」中,另一個在Role「RegisteredUser」中。

我做了一個Ajax動作,啓用/禁用並設置鎖定DateTime.MaxValue只是爲了測試特定的「RegisteredUser」。它在某些View中僅供管理員使用。

如果某些「RegisteredUser」在登錄時被「Admin」鎖定,我想在他的下一個請求或至少60分鐘後顯示「RegisteredUser」鎖定頁面。

現在我聽說過Global.asax中的AuthorizationFilter和ActionFilter或者一些事件處理函數。但也許已經有一些機制來禁用用戶,並立即反映在目標用戶角色上?

如何最好地實現鎖定/禁用用戶立即執行的問題。

回答

0

我會使用實現OnActionExecuting的基本控制器。此時,您可以檢查用戶是否需要將redirected鎖定到鎖定屏幕。

+0

嗯....這當然是一種方法,但我走了另一個解決方案,因爲我不想經常檢查數據庫。 – Dino

0

鎖定用戶時,我也更改了SecurityStamp,這將導致auth cookie失效。可以在Startup.Auth中找到Integrated Identity 2.0機制,每次(默認:30分鐘)檢查cookie的完整性,如果無效則退出用戶(例如,具有不同SecurityStamp的cookie)。檢查的時間延遲可以改變,但我認爲它適合我的項目。

這部分代碼會使某些用戶的cookie無效,並且我會每天安排一些檢查,如果檢測結果爲true,將會觸發它;

var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
var user = userManager.FindByName(username); 

userManager.SetLockoutEnabled(user.Id, true); 
userManager.SetLockoutEndDate(user.Id, DateTime.MaxValue); 
user.SecurityStamp = Guid.NewGuid().ToString("D"); 
userManager.UpdateSecurityStamp(user.Id); 

負責cookie驗證和/或重新生成的部分已經存在,但如果我沒有弄錯,它只能從Identity 2.0接收。它的配置是在Startup.Auth.cs文件看起來是這樣的:

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.FromMinutes(30), 
      regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) 
    } 
});  

我發現這一切都在這裏就各條款的計算器如此歸功於那些人。

Kevin Raffay的答案肯定是有效的,所以我會將它標記爲答案,因爲我對此很陌生,我不確定哪種方法更好。

相關問題