Shahid Riaz Bhatti

if(my.work == “Interesting” || my.availableTime > my.workHours) { this.blog.Post();}

How to retrieve data from Cookie

May 26
by Shahid Riaz Bhatti 26. May 2009 12:03
 

Retrieve data from Cookies

 
 

In this small article I’ll explain that how to retrieve user’s data from the cookies.

In .Net 2005 we have several API’s related to Users and Roles. For example if you want to know that a User ABC belongs to a role “XYZ”, then you can proceed as follow:

User.IsInRole(“XYZ”);

The above will return you Boolean variable.

But for a small web site on which I was working, I got a point where I was interested to know the Role of the current logged in user. I was using forms authentication and was not using the User and Role API’s which are provided in .Net 2005.

The Solution is very simple. The overall summary is given below:

1.       Retrieve the cookie which you stored, during the login process (i.e. on Login page)

2.       Now decrypt that authentication ticket

3.       And now retrieve the user’s data from the ticket.

The code is given below:

string cookieName = FormsAuthentication.FormsCookieName;

1.       HttpCookie authCookie = Context.Request.Cookies[cookieName];

2.       FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

3.       Response.Write(authTicket.UserData);

If you have assigned any role to the user, then by using authTicket.UserData you can get those roles..

Cheers,

RecentComments

Comment RSS

Most comments

supplynflshop supplynflshop
51 comments
tiffany-bracelets tiffany-bracelets
39 comments
AVI to iPad AVI to iPad
36 comments