在凭据更改时远程注销用户

Remotely log out user on credential change

我有一个管理员可以手动更改用户密码或电子邮件 address/username 的方法。

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

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

我见过的最好的例子是一个旧的 SO post:

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