【问题标题】:SimpleMembership taking away user authentication?SimpleMembership 取消用户身份验证?
【发布时间】:2013-02-10 12:47:07
【问题描述】:

我正在制作一个新的 MVC 4 网站,并且我已经设置了 SimpleMembership。我还创建了一个继承自 RolePrincipal 的 CustomPrincipal,并具有一个名为 UserInfo 的附加属性,其中包含有关用户的附加信息,例如 LastName、FirstName 和 IsActive。这些都通过 FormsAuthenticationTicket userData 属性存储在 cookie 中。

我的问题如下。假设我有一个管理页面,管理员用户可以在其中禁用其他用户的帐户 - 将 IsActive 属性设置为 false。同时假设被禁用的用户当前实际上已登录。如果他的访问权限被拒绝,我不希望该用户能够继续浏览该站点。

我怎样才能杀死他的会话意味着销毁他的 FormsAuthentication cookie?这是正确的做法还是我在 SimpleMembership 中缺少其他东西?完成这项任务的正确途径是什么?任何建议将不胜感激...

【问题讨论】:

    标签: .net asp.net-mvc-4 simplemembership


    【解决方案1】:

    我建议结合使用Application_AuthenticateRequest和ASP.NET Cache,如下:

    1) 当用户被删除时,将用户 ID 写入 ASP.NET 缓存中,它可以在其中停留一段有限的时间(可能是一天):

    string cacheKey = "RecentlyDeletedUserId" + userId;
    Cache.Add(
        cacheKey,
        true,
        null,
        DateTime.Now.AddDays(1),
        null,
        CacheItemPriority.Normal,
        null
    );
    

    2) 在 global.asax 中,您可以添加Application_AuthenticateRequest 处理程序,该处理程序在服务器成功接收到表单身份验证票证后针对每个请求 触发。在此处理程序中,您发出一个廉价的内存缓存请求,以查看该用户是否在最近删除的用户列表中。如果是,则将其注销并将其重定向到登录页面。

    protected void Application_AuthenticateRequest(object sender, EventArgs e) {
        string cacheKey = "RecentlyDeletedUserId" + userId;
        if (Cache[cacheKey] != null)
        {
            FormsAuthentication.SignOut();
            FormsAuthentication.RedirectToLoginPage();
        }
    }
    

    如果由于某种原因您不喜欢重定向方法,则可以采用以下方法:

    protected void Application_AuthenticateRequest(object sender, EventArgs e) {
        string cacheKey = "RecentlyDeletedUserId" + userId;
        if (Cache[cacheKey] != null)
        {
            IPrincipal anonymousPrincipal = new GenericPrincipal(new GenericIdentity(String.Empty), null);
            Thread.CurrentPrincipal = anonymousPrincipal;
            HttpContext.Current.User = anonymousPrincipal;
        }     
    }
    

    这只是将用户替换为匿名用户,从而确保该用户无法在您的网站上执行任何操作。 (这种替代方法来自Invalidating ASP.NET FormsAuthentication server side。)

    【讨论】:

    • 感谢您的精彩回复。我认为我更喜欢缓存的想法,因为我必须实现 UserStillValid 方法,而且我不喜欢在 global.asax 中运行业务逻辑的想法。
    • 对不起,我剪切和粘贴的太多...!UserStillValid 在第二种选择中只是检查缓存
    • 第二组代码会做什么?存储在anonymousPrincipal 中的内容。 Thread.CurrentPrincipal = anonymousPrincipal and HttpContext.Current.User = anonymousPrincipal; 而不是 signout 是什么意思?
    • 假设管理员有用户界面,管理员在其中使用户处于非活动状态,同时用户在页面中。那么 Application_AuthenticateRequest 什么时候会触发呢?它会触发任何页面请求吗?
    猜你喜欢
    • 1970-01-01
    • 2016-04-12
    • 2011-08-13
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 2014-11-29
    相关资源
    最近更新 更多