Tuesday, May 7, 2013

How to Pass Custom Data in FormsAuthenticationTicket


Lets say we have an custom object with following properties.


public class AuthUser
{
public int UserID { get; set; }
public string UserNo { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public override string ToString()
{
return UserID + "," + UserNo + "," + UserName + "," + Password;
}
}

To pass custom data with the authentication ticket use below code.

AuthUser au = new AuthUser();
au.UserID = 1;
au.UserNo ="001";
au.UserName = "chamara";
au.Password = "123";
string userData = au.ToString();

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(

2, // Version number

txtUserName.Text.Trim(), // Username

DateTime.Now, // Issue date

DateTime.Now.AddDays(555), // Expiration date

false, // Persistent?

userData // User data
);

Retrieve Userdata

FormsIdentity id = (FormsIdentity)Context.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string[] UserData = ticket.UserData.Split(',');

No comments:
Write comments
Recommended Posts × +