Search code examples
cookiessession-fixation

Update cookie after authentication


Ours is a web application. The security team has suggested us to change cookie upon every escalation in the authorization.

Accordingly, I wanted to update the client side cookie after authentication. And I used the below code:

  System.Web.HttpCookie cookie = Request.Cookies["ASP.NET_SessionId"];
  System.Web.HttpCookie dummyCookie = new System.Web.HttpCookie("SessionId");
  cookie.Value = dummyCookie.Value;
 Response.Cookies.Add(cookie);

Problem is as soon as the cookie gets updated, the user is again taken as an unauthenticated user.

Thanks in advance.


Solution

  • I have implemented like below to handle this in my project.

    When user browse the application login page. I am deleting the sessionid in the session-cookie using below code in the page load.

    if(!IsPostBack)
    {
                HttpContext.Current.Session.Clear();
                HttpContext.Current.Session.Abandon();
                HttpContext.Current.Session.RemoveAll();
                Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
    }
    

    The above code will empty the sessionid in the session cookie. Now when user enter the appropriate credentials asp.net will create new session id automatically, so browser will get new session upon successful authentication. If user entered wrong credentials then using above code i am resetting the sessionid again so the new sessionid will automatically generated up on successful authentication.

    Security tools no more showing session fixation issue after above implementation was in place in my project. I hope this helps.