title: Log Out a User in MVC 5 Using a Custom ActionFilterAttribute
body: <p>I have a custom ActionFilterAttribute that makes sure a value in the Session matches a value in the database.  If the values don't match, it redirects the user to the Login action on the AccountController.</p>
  
  <pre><code>public class CheckSessionAttribute : ActionFilterAttribute, IAuthenticationFilter
  {
      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
          if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Any())
          {
              // If the action allows Anonymous users, no need to check the session
              return;
          }
  
          var session = filterContext.RequestContext.HttpContext.Session;
          var userName = filterContext.RequestContext.HttpContext.User.Identity.Name;
  
          var userStore = new ApplicationUserStore(new IdentityDb());
          var userManager = new ApplicationUserManager(userStore);
  
          var user = userManager.FindByNameAsync(userName).Result;
  
          if (userName == null || user == null || session == null || session["ActiveSessionId"] == null || 
              session["ActiveSessionId"].ToString() != user.ActiveSessionId.ToString())
          {
              session.RemoveAll();
              session.Clear();
              session.Abandon();
  
              filterContext.Result = new RedirectToRouteResult(
                  new RouteValueDictionary(new
                  {
                      action = "Login",
                      controller = "Account"
                  }
              ));         
          }
  
          base.OnActionExecuting(filterContext);
      }
  }
  
  [Authorize]
  public class AccountController : Controller
  {
      [AllowAnonymous]
      public ActionResult Login(string returnUrl)
      {
          SignOutAndKillSession();
          ViewBag.ReturnUrl = returnUrl;
          return View();
      }
  
      private void SignOutAndKillSession()
      {
          AuthenticationManager.SignOut();
          Session.RemoveAll();
          Session.Clear();
          Session.Abandon();
      }
  }
  </code></pre>
  
  <p>When I try to login again after being redirected to the Login action, I get the following exception:</p>
  
  <pre><code>The provided anti-forgery token was meant for a different claims-based user than the current user
  </code></pre>
  
  <p>I set a breakpoint inside the Login action and can see that User.Identity.Name is still set to the user that is being logged out, before AND after the call SignOutAndKillSession(). I believe this is what's causing an incorrect AntiForgeryToken to be generated when the page renders.  </p>
  
  <p>Can someone help me find out how to clear the User Principal when logging out a user?  </p>
  
  <p>Thanks</p>