May 26

How to retrieve data from Cookie

ASP.Net | C# 105 Comments »

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
 

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,



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , ,

Comments

Add comment


(Will show your Gravatar icon)  

biuquote
  • Comment
  • Preview
Loading