凭据更改时远程注销用户
本文关键字:注销 用户 程注销 | 更新日期: 2023-09-27 18:09:30
管理员可以手动更改用户的密码或电子邮件地址/用户名。
但是,如果用户一直在使用该应用程序并且拥有一个验证cookie,那么当他们返回站点时,即使他们的密码已经更改,他们仍然会使用该应用程序进行身份验证。
如何强制这些用户的cookie被标记为无效,并在他们加载新页面时强制重新认证?
我见过的最好的例子是一个旧的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()没有将用户注销
这是添加逻辑作为所有用户过滤器的起点。
首先,您需要创建自定义动作过滤器属性:
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();
}
}
或者,您可以将其作为全局过滤器添加到每个请求中。如果你这样做,请确保在onactionexecution中添加一个检查,以在验证之前验证用户是否经过身份验证。
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new CheckForLogoutAttribute()); // Add for every request
}
}