【问题标题】:How to force user sign out on lockout in MVC5如何在 MVC5 中强制用户退出锁定
【发布时间】:2017-10-04 02:34:49
【问题描述】:

我正在使用带有 Identity 的 .Net MVC5,并且对开发人员来说是新手,所以请多多包涵。

如何显示锁定页面并根据锁定状态强制用户退出?

出于测试目的,我创建了两个用户,一个在“Admin”角色中,另一个在“RegisteredUser”角色中。

我做了一个 Ajax 操作来启用/禁用并将锁定设置为 DateTime.MaxValue,只是为了测试特定的“RegisteredUser”。它连接在某些视图中,仅供管理员使用。

如果某些“RegisteredUser”在登录时被“Admin”锁定,我想在“RegisteredUser”下次请求时或至少 60 分钟后显示锁定页面。

现在我听说了 AuthorizationFilter 和 ActionFilter 或者 Global.asax 中的一些事件处理程序。但也许已经有一些机制可以禁用用户并立即反映在目标用户角色上?

如何通过立即执行来最好地解决锁定/禁用用户的问题。

【问题讨论】:

    标签: asp.net identity asp.net-mvc-5


    【解决方案1】:

    我会使用实现OnActionExecuting 的基本控制器。此时,您可以检查用户是否需要redirected 才能进入锁定屏幕。

    【讨论】:

    • 嗯....这当然是一种方法,但我选择了另一种解决方案,因为我不想经常检查数据库。
    【解决方案2】:

    在锁定用户的同时,我还更改了 SecurityStamp,这将导致 auth cookie 无效。可以在 Startup.Auth 中找到的集成身份 2.0 机制每隔(默认:30 分钟)检查 cookie 完整性,如果无效(例如,具有不同 SecurityStamp 的 cookie),则注销用户。检查的时间延迟可以更改,但我认为它适合我的项目。

    这部分代码使一些用户的 cookie 无效,我每天安排一些检查,如果为真,就会触发它;

    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))
        }
    });     
    

    我在 stackoverflow 上的不同文章中找到了所有这些内容,因此归功于这些人。

    Kevin Raffay 的回答肯定有效,所以我将其标记为答案,因为我是新手,我不确定哪种方法更好。

    【讨论】:

    • 我需要在哪个函数下编写这一行 userManager.SetLockoutEnabled(user.Id, true); ?
    • 如果用户使用其他浏览器登录会怎样。如何强制用户退出?
    猜你喜欢
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多