Anas Ghanem

ASP.NET from the middle east

Syndication

Sponsors

News


    Subscribe in a reader
Changing the session ID programmatically.

In this blog, I will show how to change the Assigned session Id programmatically.

You may ask : why I need to change the automatically generated the user session id ? well there is many possible reasons like :

  • You may use the session ID to track the User activities or to implement audit trails in your system.
  • Preventing Session Hijacking by generating a new session id after the user logged in.
  • Removing the user session after logging out.

There could be more reasons that I don't know about them , if you know more reasons feel  free to post it in the comments section .

Changing the Session id is an easy task in asp.net.You just need to use SessionIDManager class.

The class contains a lot of helpful methods ,I will list some of them :

  • CreateSessionID : returns a unique session identifier that is a randomly generated number encoded into a 24-character string.
  • GetSessionID :  gets the session-identifier value from the current Web request.
  • SaveSessionID : saves a newly created session identifier to the HTTP response.

The rest of methods and class members can be found here.

I will now show a simple code that will print the Current SessionId and Create a new session id and save it to the context.

[Code provided in C# ]

        SessionIDManager Manager = new SessionIDManager();
 
        string NewID = Manager.CreateSessionID(Context);
        string OldID = Context.Session.SessionID;
        bool redirected = false;
        bool IsAdded = false;
        Manager.SaveSessionID(Context, NewID,out redirected, out IsAdded);
        Response.Write("Old SessionId Is : " + OldID);
        if (IsAdded)
        {
            Response.Write("<br/> New Session ID Is : " + NewID);
        }
        else
        {
            Response.Write("<br/> Session Id did not saved : ");
        }

Hope it helps.

Published Tuesday, December 16, 2008 10:48 PM by anas
Filed under: ,

Comments

# re: Changing the session ID programmatically.@ Friday, December 19, 2008 12:17 PM

The last two parameters to the SaveSessionID method are "out" parameters, so your code won't even compile. You need to change it to:

bool isRedirected, cookieAdded;

Manager.SaveSessionID(Context, NewID, out isRedirected, out cookieAdded);

# re: Changing the session ID programmatically.@ Friday, December 19, 2008 12:58 PM

Thanks ,

I fixed the code.

Actually the code was originally written in VB ,it was converted to c# using a tool.

by anas

Leave a Comment

(required) 
(required) 
(optional)
(required)