2017-05-05 59 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的答案肯定是有效的,所以我会将它标记为答案,因为我对此很陌生,我不确定哪种方法更好。