How to unauthenticate current user ASP.net mvc Identity

冷暖自知 提交于 2019-12-06 01:24:11

This is probably happening because the page is getting cached and the anti-forgery token that was generated for an anonymous user can't be validated against the logged in user.

Try sticking the OutputCache (ResponseCache in core) attribute on your Login GET and this will set the right headers to not cache the page.

[OutputCache(NoStore = true, Duration = 0, Location = OutputCacheLocation.None)]
public ActionResult Login(string returnUrl)
{
    ...
}

I solved this by doing a combination of two things.

Problem 1: I noticed that When I hit the back btn and the login view was displayed, the previous users cookie was not destroyed. This only occured in chrome but not in IE. This was solved with [OutputCache(NoStore = true, Duration = 0, Location = OutputCacheLocation.None)] attribute on my Login Get (Thanks @Shoe). See code below.

Login:

// GET: /Account/Login
    [AllowAnonymous]
    [OutputCache(NoStore = true, Duration = 0, Location = OutputCacheLocation.None)]
    public ActionResult Login(string returnUrl)
    {
        EnsureLoggedOut();

        // Store the originating URL so we can attach it to a form field
        var viewModel = new LoginViewModel { ReturnUrl = returnUrl };

        return View(viewModel);
    } 

Problem 2: The second problem was that once the login view was displayed, I called a method to signout the user with AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie); and Session.Abandon();. This was not unauthenticating the user until I hit the refresh button for a reason I don't understand. Not until I add a second step to clear the principal to ensure the user does not retain any authentication by adding HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null); to my EnsureLoggedOut method. See code below.

EnsureLoggedOut Method:

private void EnsureLoggedOut()
    {
        if (AuthenticationManager.User.Identity.IsAuthenticated)
        {
            //SignOut the current user
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie);
            Session.Abandon();

            // Second we clear the principal to ensure the user does not retain any authentication
            HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!