How to expire Authentication Cookie in ASP.NET MVC5.

2023-06-26T06:37:49.96+00:00

I'm trying these following code.

I use AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie) to SignOut the web page.

But It's seem to doesn't work correctly, It could access again in same http request including with using same Authentication Cookie.

how do I change the code for fix this matter.

        // POST: /Account/LogOff
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
 
            Session.RemoveAll();
            Session.Abandon();
            Session.Clear();

            Response.Cookies.Clear();

            return RedirectToAction("Index", "Home");
        }
Developer technologies ASP.NET Other
{count} votes

2 answers

Sort by: Most helpful
  1. Ryan Jusay 165 Reputation points
    2023-06-26T10:16:03.28+00:00

    Add this after your line:

    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

        // Expire the cookie by setting its expiration date to a past date
        var cookie = new HttpCookie("YourAuthCookieName")
        {
            Expires = DateTime.UtcNow.AddDays(-1)
        };
        
        // Add the expired cookie to the response to update the client's cookie
        Response.Cookies.Add(cookie);
    

    Make sure to replace "YourAuthCookieName" with the actual name of your authentication cookie.

    1 person found this answer helpful.
    0 comments No comments

  2. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-06-26T14:50:49.91+00:00

    Your scenario is not clear. The delete cookie, just sends the cookie back to the browser as expired. The cookie is not invalided, the browser just will not send it anymore. If you are using a tool, it may not honor the delete.

    also if you are using single sign on, often the login server has its own cookie, so it can login the user without asking for credentials. If home/index requires authentication, than this could be happening.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.