SimpleMembership是否取消了用户身份验证?

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

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

如何杀死他的会话,意味着销毁他的FormsAuthentication cookie?这样做是否正确,还是SimpleMembership中还有其他内容我没有注意到?实现此任务的正确方法是什么?任何建议都将不胜感激...

1个回答

3
我建议将Application_AuthenticateRequest和ASP.NET Cache结合使用,具体操作如下:
1)当用户被删除时,将用户ID写入ASP.NET Cache中,并在一定时间内保留(例如一天):
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中运行业务逻辑的想法。 - Marko
1
抱歉,我复制粘贴了太多...在第二个替代方案中,!UserStillValid 只是检查缓存。 - J.T. Taylor
第二组代码将会做什么?anonymousPrincipal 中存储了什么?Thread.CurrentPrincipal = anonymousPrincipalHttpContext.Current.User = anonymousPrincipal; 的含义是什么?这代表着注销吗? - Thomas
假设管理员有一个用户界面,可以使用户无效,并且同时用户在页面上。那么当Application_AuthenticateRequest触发时呢?它是否会为任何页面请求触发? - Thomas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接