How to get Cookieless FormsAuthentication to work with self-issued FormsAuthenticationTickets and custom UserData

This question was asked by Scott recently.

Short answer: you can :)

The trick is to do a Response.Redirect with an appended query string in the following format:

~/Page.aspx?{0}={1}

where

{0} = forms ticket name
{1} = encrypted forms ticket string

in addition you have to set enableCrossAppRedirects to true in the forms auth config.

Here is some code (e.g. behind your login button):

  // access forms auth configuration

  AuthenticationSection section = (AuthenticationSection)

    ConfigurationManager.GetSection(“system.web/authentication”);

  TimeSpan timeout = section.Forms.Timeout;

       

  // create ticket with user data

  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(

    1,

    _txtName.Text,

    DateTime.Now,

    DateTime.Now.Add(timeout),

    false,

    “user defined data”);

 

  // encrypt ticket

  string encTicket = FormsAuthentication.Encrypt(ticket);

  string ticketName = FormsAuthentication.FormsCookieName;

       

  // do the redirect

  Response.Redirect(String.Format(“{0}?{1}={2}”,

    FormsAuthentication.DefaultUrl,

    ticketName,

    encTicket));

 

The above code has one disadvantage. For some reason, the forms auth timeout is not exposed via the FormsAuthentication class and you have to access the configuration element to retrieve it. This in turn requires ConfigurationPermission which you only have in Full and High trust.

 

On the next roundtrip you can access the user data as normal:

 

if (Request.IsAuthenticated)

{

  FormsIdentity id = Context.User.Identity as FormsIdentity;

 

  FormsAuthenticationTicket ticket = id.Ticket;

  string userData = ticket.UserData;

}

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s