I have a method for an administrator to change a user's password or email address/username manually.
However, if the user has been using the application and has an auth cookie, when the come back to the site, they'll still be authenticated with the application, even though their password has changed.
How can I force these users' cookies to be flagged as invalid, and force re-authentication when they load a new page?
Best example I've seen has been an old 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();
Source: FormsAuthentication.SignOut() does not log the user out
UPDATE
Here's a starting point to add your logic as a filter for all users.
First, you need to create the custom action filter attribute:
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
}
}
Then you can add this filter into specific controllers for each action in the controller or just for only specific actions.
[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();
}
}
Or, you can add to it to every request as a global filter. If you do this, be sure to add a check into your OnActionExecuting to verify the user is authenticated before your validation.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new CheckForLogoutAttribute()); // Add for every request
}
}