Real world ASP.NET authentication

Hello everyone,

I’m here to say that most of ASP.NET books on the market didn’t provide you the effective way to use authentication cookies.

Assume that when you’re working with form-based authentication. (Setting in web.config) When we do some manual authentication method, we imports System.Web.Security and using FormsAuthentication.RedirectFromLoginPage(”userName”, false). The ASP.NET authentication engine will automatically create a cookie to persist authenticate status. This cookies was used to identify the user have been signed in or not. So, when we want to store some of user’s profile. How do we do it?

We can coding to create new cookie object to store those profile but we already known that ASP.NET authentication engine already created the cookie when signed in. The question should be “How do we access this cookie? Is it possible?”.

Certainly, you can do it. Please review the following code.

In your login button’s click event.

if(AuthSucceeded)

{

HttpCookie cookie = FormsAuthentication.GetAuthCookie(txtLoginName.Text, false);

FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

FormsAuthenticationTicket newticket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, “Secret|Role|CustomVar1″, ticket.CookiePath);

cookie.Value = FormsAuthentication.Encrypt(newticket);

Context.Response.Cookies.Set(cookie);

}

The above code was used to create an authenticated cookie with custom profile/data. (”Secret|Role|CustomVar1″)

When we need to extract the custom profile/data, we do with the following code.

FormsIdentity ident = (FormsIdentity)User.Identity;

string strCustomData = ident.Ticket.UserData.ToString();

With this method, we don’t need any separated cookies to store the authenticated user’s profile anymore.

Hope this help you get step ahead on your ASP.NET skill.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists

Leave a Comment