Anti-Forgery Token was meant for a different claims-based user

前端 未结 7 1809
有刺的猬
有刺的猬 2020-12-28 13:41

I am working on a logout feature in the application we are using ASP.NET Identity login. I can login successfully but when I logout and then try to login again I get the fol

7条回答
  •  抹茶落季
    2020-12-28 14:11

    I found that users were experiencing this issue when they would submit the login page when already authenticated. I replicated this error by:

    1. Opening two tabs when logged in,
    2. Logging out from one,
    3. Reloading both,
    4. Logging in to one,
    5. Trying to log in with the other. The error occurred before entry to the POST: /Account/Login action.

    The majority of my users use the web app on a mobile device, so it made sense that they had bookmarked the login page and pulled it up and submitted when they had a tab opened in the background already logged in. I also surmised that sometimes they would have a dormant tab loaded with the login form and just pull that tab up and submit.

    I realize that there are many ways to solve this issue. I solved this with two changes:

    1. I added a check on User.Identity.IsAuthenticated to my "GET: /Account/Login" action:
    if (User.Identity.IsAuthenticated)
    {
       try
       {
          return RedirectToLocal(returnUrl);
       }
       catch
       {
          return RedirectToAction("index", "Home");
       }
    }
    
    1. In my controller I created a "check if logged in" action:
    [AllowAnonymous]
    public JsonResult CheckLogedIn()
    {
        try
        {
            return Json(new { logged_in = User.Identity.IsAuthenticated }, JsonRequestBehavior.AllowGet);
        }
        catch
        {
            return Json(new { logged_in = false }, JsonRequestBehavior.AllowGet);
        }
    }
    

    And I called it repeatedly in the view to redirect all open login forms away from the login page when already logged in:

    
    

    This worked well for me. Hope it helps you.

提交回复
热议问题