ASP.net Authentication question

anonymous_at_discussions.microsoft.com
Date: 03/23/04


Date: Tue, 23 Mar 2004 03:56:57 -0800

The snipeet below is from MSDN library's arcticle

>From Solution Explorer, open global.asax.
Switch to code view and add the following using statements
to the top of the file:
using System.Web.Security;
using System.Security.Principal;

Locate the Application_AuthenticateRequest event handler
and add the following code to obtain the forms
authentication cookie from the cookie collection passed
with the request.
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies
[cookieName];

if(null == authCookie)
{
  // There is no authentication cookie.
  return;
}

Add the following code to extract and decrypt the
authentication ticket from the forms authentication
cookie.
FormsAuthenticationTicket authTicket = null;
try
{
  authTicket = FormsAuthentication.Decrypt
(authCookie.Value);
}
catch(Exception ex)
{
  // Log exception details (omitted for simplicity)
  return;
}

if (null == authTicket)
{
  // Cookie failed to decrypt.
  return;
}

Add the following code to parse out the pipe separate list
of role names attached to the ticket when the user was
originally authenticated.
// When the ticket was created, the UserData property was
assigned a
// pipe delimited string of role names.
string[] roles = authTicket.UserData.Split(new char[]
{'|'});

Add the following code to create a FormsIdentity object
with the user name obtained from the ticket name and a
GenericPrincipal object that contains this identity
together with the user's role list.
// Create an Identity object
FormsIdentity id = new FormsIdentity( authTicket );

// This principal will flow throughout the request.
GenericPrincipal principal = new GenericPrincipal(id,
roles);
// Attach the new principal object to the current
HttpContext object
Context.User = principal;