4

I am trying to get a new value for the Session Cookie for every new login. Basically, the value in the screenshot below should have a new random string every time a user logs in. This is to avoid Session Fixation.

I have tried the following :

On login :

Response.Cookies.Delete(".AspNetCore.Session");

HttpContext.Request.Cookies[".AspNetCore.Session"] = "123132" //does not allow to be set

On log out :

HttpContext.Session.Clear();

Response.Clear();

Session.Abandon() // Abandon is no longer available

But the value of the Session Cookie just does not change. Any guidance is greatly appreciated.

Session Cookie on Browser Inspect

Rakendu
  • 43
  • 1
  • 5

1 Answers1

5

Try to use Response.Cookies.Delete(".AspNetCore.Session"); in Logout to delete the cookie

Below is a work demo, you can refer to it,

On login :

Response.Cookies.Append("Test_cookie", "yo");

On log out :

 Response.Cookies.Delete("Test_cookie");

Result:

enter image description here

Qing Guo
  • 6,041
  • 1
  • 2
  • 10
  • Thanks for your response. Somehow, my AspNetCore.Session cookie does not get deleted along with the TestCookie. Is there some setting that could be stopping it from being cleared? Also, can i check, when the AspNetCore.Session reappears on login, is the value same as what was before logoff or is it a new value? – Rakendu May 30 '22 at 02:41
  • @Rocky Did you use "Response.Cookies.Delete(".AspNetCore.Session");" in Logout to delete the cookie? – Qing Guo May 30 '22 at 02:48
  • How do you set the value of the AspNetCore.Session ? – Qing Guo May 30 '22 at 02:54
  • Thanks! That worked. I added Response.Cookies.Delete(".AspNetCore.Session"); on logout and there is a new value on login! :D Can you please update your answer so that i can accept it. – Rakendu Jun 01 '22 at 05:44
  • I do not explicitly set it, I have the following code on startup.cs which i think sets the session cookie ` services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(60); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; });` – Rakendu Jun 01 '22 at 05:46