OWIN - Authentication.SignOut() doesn't seem to remove the cookie

54,912

Solution 1

I had a similar problem for the past few days. Instead of

Request.GetOwinContext().Authentication.authenticationManager.SignOut();

Use ONE(and only one) of these:

Request.GetOwinContext().Authentication.SignOut();

Request.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);

HttpContext.Current.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);

This article explains why your cookies don't get deleted: https://dzone.com/articles/catching-systemwebowin-cookie

I know my answer isn't the most research-based, but to tell you the truth, I just couldn't find WHY my provided code examples work for me. I just know that System.Web messes up Owins cookies if you do SignOut() another way.

Solution 2

This worked for me. Throw it into a controller when you want to invalidate the cookie. In particular, I used this to update the user's roles so that the user doesn't have to manually log out and back in again to fix menus that get loaded under @if(User.IsInRole("Admin")){...}. I hope this helps someone - it took me a while to figure this out.

    var updatedUser = await UserManager.FindByNameAsync(User.Identity.Name);
    var newIdentity = await updatedUser.GenerateUserIdentityAsync(UserManager);
    AuthenticationManager.SignOut();
    AuthenticationManager.SignIn(newIdentity);
Share:
54,912
jaeyow
Author by

jaeyow

Updated on August 02, 2022

Comments

  • jaeyow
    jaeyow over 1 year

    I'm having some issues with OWIN Cookie authentication. I have a .Net site that has some MVC pages which uses cookie authentication and WebAPI resources protected by a bearer token.

    When I log out, I delete the access token on the client, so subsequent API requests will not have the token in the header and will thus fail the authentication. This part is fine.

    In the same manner, I would also like the log out to delete the cookie used by the MVC pages. I did the following on the server:

        [Route("Logout")]
        public IHttpActionResult Logout()
        {
            var ctx = Request.GetOwinContext();
            var authenticationManager = ctx.Authentication;
            authenticationManager.SignOut();
            return Ok();
        }
    

    However, after the calling Logout, I can still visit the protected MVC page even though the cookie would have supposedly been deleted by the Logout call.

    It seems so simple, so I might have missed something.

    Thanks,