Description
Many web applications display the username at the upper right hand corner to let the user know that they are logged in. This information is stored within the User.Identity.Name property. I like to load all their basic information such as name, email, date they last logged in, and date they last updated their profile. This way, I don't have to go to the user store (database) everytime this common information is requested.
Since an authorization ticket is created when the user is authenticated, why not store the additional information in the same place? We can use the UserData property and like other ticket properties, it is encrypted based on your web configuration file. You will need to determine how you wish to serialize the additional information into a string.
Code
protected void LoginAction_Click(object sender, EventArgs e)
{
Page.Validate();
if (!Page.IsValid) return;
bool blnIsPersistent = false;
string strUserName = txtUserName.Text.Trim();
string strPassword = txtPassword.Text.Trim();
if (this.Authenticate(strUserName, strPassword))
{
HttpCookie authCookie =
FormsAuthentication.GetAuthCookie(
strUserName,
blnIsPersistent
);
FormsAuthenticationTicket authTicket =
FormsAuthentication.Decrypt(
authCookie.Value
);
// retrieve from user store
string strUserData = "data";
// create new ticket
FormsAuthenticationTicket authTicket =
new FormsAuthenticationTicket(
authTicket.Version,
authTicket.Name,
authTicket.IssueDate,
authTicket.Expiration,
authTicket.IsPersistent,
strUserData,
authTicket.CookiePath
);
authCookie.Value =
FormsAuthentication.Encrypt(authTicketNew);
Response.Cookies.Add(authCookie);
Response.Redirect(
FormsAuthentication.GetRedirectUrl(
authTicketNew.Name,
authTicketNew.IsPersistent
)
);
}
else
{
// do something...
}
}
You can access the UserData from another page with the following:
FormsIdentity identity = User.Identity as FormsIdentity;
Response.Write(identity.Ticket.UserData);

2 comments:
I've been totally looking for something like this!
Very Cool Ryan, I have to take an in depth look at it all, there is a lot of info!!
LC
Post a Comment