Export (0) Print
Expand All

AuthenticationService.CreatingCookie Event

Occurs when the authentication cookie is being set.

Namespace:  System.Web.ApplicationServices
Assembly:  System.Web.Extensions (in System.Web.Extensions.dll)

public static event EventHandler<CreatingCookieEventArgs> CreatingCookie

The CreatingCookie event is raised when the authentication cookie is being set after user credentials have been validated. Create an event handler for the CreatingCookie event to customize the authentication cookie.

The following example shows how to bind an event handler to the CreatingCookie event in the Application_Start method of the Global.asax file.


void Application_Start(object sender, EventArgs e)
{
    System.Web.ApplicationServices.AuthenticationService.CreatingCookie 
        += new EventHandler<System.Web.ApplicationServices.CreatingCookieEventArgs>
        (AuthenticationService_CreatingCookie);
}


The following example shows an event handler for the CreatingCookie event in the Global.asax file. The event handler customizes the authentication cookie by adding the value in the CustomCredential property to the UserData property. Store the CustomCredential property in a cookie only if you know that the data in the property is not sensitive. Malicious users can access the values in the cookie.


void AuthenticationService_CreatingCookie(object sender, 
    System.Web.ApplicationServices.CreatingCookieEventArgs e)
{
    FormsAuthenticationTicket ticket = new
          FormsAuthenticationTicket
            (1,
             e.UserName,
             DateTime.Now,
             DateTime.Now.AddMinutes(30),
             e.IsPersistent,
             e.CustomCredential,
             FormsAuthentication.FormsCookiePath);

    string encryptedTicket =
         FormsAuthentication.Encrypt(ticket);

    HttpCookie cookie = new HttpCookie
         (FormsAuthentication.FormsCookieName,
          encryptedTicket);
    cookie.Expires = DateTime.Now.AddMinutes(30);

    HttpContext.Current.Response.Cookies.Add(cookie);
    e.CookieIsSet = true;
}


.NET Framework

Supported in: 4, 3.5

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Community Additions

ADD
Show:
© 2014 Microsoft