Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change session id after login in asp.net

I have a website that's using forms authentication and membership. A user must have cookies enabled to use the site. I've been asked to change the code so that the session id is changed as soon as a user logs in. Aparently this will protect against a Session Fixation attack (http://en.wikipedia.org/wiki/Session_fixation). Does anyone know how I can change the session id without losing the whole session ? PHP has a specific method for doing this but I can't find a .NET equivalent.

like image 596
MemoryLeak Avatar asked Sep 14 '09 01:09

MemoryLeak


People also ask

Can we change session ID?

In this case, the function session_regenerate_id() just changes the current session ID but leaves all data intact. This is shown in the preceding code, in which the current session ID (both old and new) is retrieved using the session_id() function.

How we can change ASP NET_SessionId after login the application?

Add(new HttpCookie("ASP. NET_SessionId", "")); This code example clears the session state from the server and sets the session state cookie to null. The null value effectively clears the cookie from the browser.

Why should you reset the session ID after a successful login?

Yes. You should regenerate the session on login, to help defend against session fixation and login CSRF.

Why does the session ID changes in every request?

When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed.


3 Answers

Here's a blog post that talks about this:

ASP.NET does not directly support functionality to regenerate a session ID. See the documentation regarding the issue here. There is a not-so quick and dirty way to do it by setting the ASPNET_SessionID value to the empty string and redirecting so that the value is regenerated.

like image 57
Druid Avatar answered Sep 22 '22 09:09

Druid


I have answered a similar question at Generating a new ASP.NET session in the current HTTPContext. Basically we must change some of the SessionStateModule internal state to be able to regenerate session ID without losing objects in the Session. I used reflection to set the _rqId field to the new ID and _rqSessionStateNotFound to true. The downside is we must grant "Full Trust" to the Application.

like image 26
YudhiWidyatama Avatar answered Sep 24 '22 09:09

YudhiWidyatama


This is a really old question I'm resurrecting, but here's the solution:

var manager = new SessionIDManager();
bool redirected, isAdded;
manager.SaveSessionID(System.Web.HttpContext.Current, 
    "5vonjb4mtb1of2fxvhjvkh5d", out redirected, out isAdded);

// sessionId now equals "5vonjb4mtb1of2fxvhjvkh5d"
var sessionId = Session.SessionID;
like image 43
Scott Avatar answered Sep 26 '22 09:09

Scott