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.
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_SessionIDvalue to the empty string and redirecting so that the value is regenerated.
-
1i aslo think about this, but after regenerate that ,all the object in session object will lose... – MemoryLeak Sep 14 '09 at 03:05
-
5The blog post you link to is no longer available. – Larry Silverman Jul 28 '16 at 15:08
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.
- 1
- 1
- 1,609
- 16
- 14
-
2The [accepted answer](http://stackoverflow.com/a/1419508/295686) references an article targeted at .NET 1.1 (and it doesn't actually address the session fixation, only old session ID reuse), but this solution was more elegant and worked in our .NET 4.5 application (one MVC site and one Web Forms site). – mlhDev Apr 23 '15 at 20:59
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;
- 13,523
- 20
- 89
- 148
-
I know, it's been some time. But we tried your code and it's not working for us. sessionId is not equals to "5vonjb4mtb1of2fxvhjvkh5d". – mosquito87 Jul 03 '13 at 06:35
-
i did this with success. sessionid does changed to the new sessionid. – pinopino Jul 25 '13 at 06:41
-
2This got us closer but not close enough - still working on it. This does update the session ID and send down the cookie update just like you'd expect but we'd still like to use the session during that same request. We aren't able to do that right now - appears the session bag is the prior one; the next request sees the new session bag but our values aren't there. – mlhDev May 27 '14 at 20:40