【问题标题】:Remotely log out user on credential change在凭据更改时远程注销用户
【发布时间】:2015-11-18 04:59:09
【问题描述】:

我有一种方法让管理员手动更改用户的密码或电子邮件地址/用户名。

但是,如果用户一直在使用该应用程序并且有一个身份验证 cookie,那么当他们返回该站点时,即使他们的密码已更改,他们仍将通过该应用程序进行身份验证。

如何强制将这些用户的 cookie 标记为无效,并在他们加载新页面时强制重新验证?

【问题讨论】:

    标签: c# asp.net asp.net-mvc cookies forms-authentication


    【解决方案1】:

    我见过的最好的例子是旧的 SO 帖子:

    FormsAuthentication.SignOut();
    Session.Abandon();
    
    // clear authentication cookie
    HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
    cookie1.Expires = DateTime.Now.AddYears(-1);
    Response.Cookies.Add(cookie1);
    
    // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
    HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
    cookie2.Expires = DateTime.Now.AddYears(-1);
    Response.Cookies.Add(cookie2);
    
    FormsAuthentication.RedirectToLoginPage();
    

    来源:FormsAuthentication.SignOut() does not log the user out

    更新

    这是将逻辑添加为所有用户的过滤器的起点。

    首先,您需要创建自定义操作过滤器属性:

    public class CheckForLogoutAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Called by the ASP.NET MVC framework before the action method executes.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // filterContext.HttpContext may be needed for request/response
            // If using the global filter setup, be sure to confirm user is logged in first
        }
    }
    

    然后您可以将此过滤器添加到特定控制器中,以针对控制器中的每个操作或仅针对特定操作。

    [CheckForLogout] // You can add it to specific controller(s)
    public class HomeController : Controller
    {
        [CheckForLogout] // Or you can do it only on certain action(s)
        public ActionResult Index()
        {
            return View();
        }
    }
    

    或者,您可以将其添加到每个请求中作为全局过滤器。如果您这样做,请务必在您的 OnActionExecuting 中添加一个检查,以在您验证之前验证用户是否已通过身份验证。

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new CheckForLogoutAttribute()); // Add for every request
        }
    }
    

    【讨论】:

    • 我看不出这不适用于当前用户的原因,但是,我正在寻找管理员重置可能或可能未登录的其他用户的身份验证 cookie现在。我在这里忽略了解决方案吗?
    • 您需要在数据库中设置一个标志,并确保您的应用在每个请求上检查用户级标志(通过 MVC 中的过滤器轻松添加,您可以在全局或所需的控制器/操作中添加) 将在用户下一次请求退出时为用户运行此代码。
    • 如果您使用数据库作为会话存储而不是 inproc 或状态服务器,您可能会在数据库中终止该用户的会话。
    • 这是假设应用程序是基于问题标签的 MVC 应用程序。您将扩展“ActionFilterAttribute”类以创建“自定义操作过滤器”(谷歌搜索有很多很好的示例)并覆盖“OnExecuting”方法以使您的逻辑检查标志。然后将该属性添加到 app_start 的 FilterConfig 中的全局过滤器(或基于您的项目的 global.asax),或者作为控制器或操作的属性。我会在答案中举个例子。
    • 刚刚添加了示例以帮助您入门。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    相关资源
    最近更新 更多