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

时间:2015-08-24 17:12:14

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

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

但是,如果用户一直在使用该应用程序并且有一个auth cookie,那么当他们回到该网站时,他们仍然会使用该应用程序进行身份验证,即使他们的密码已经更改。

我如何强迫这些用户' cookie被标记为无效,并在加载新页面时强制重新验证?

1 个答案:

答案 0 :(得分:2)

我见过的最好的例子是旧的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
    }
}