Monday, July 03, 2006

Build your own Forms Authentication

The authentication ticked is created with the FormsAuthenticationTicket class. Its constructor accepts the following parameters:

version : The version of the authentication ticket[this value will be one]
name : The user name associated with the authentication ticket
issueDate : The date that the authentication ticket was issued
expiration : The date that the authentication ticket should expire
isPersistent: A boolean value indicating whether to allow the ticket to persist
after the user closes the browser
userData : A string value of any data that you would like to store. For eg.,
say your email ID.

Add an asp.net form, with a button 'Create Ticket'. On click on this button invoke the 'Login' method.

void Login(Object s, EventArgs e)
{
if (txtUsername.Text == "xxx" && txtPassword.Text == "xxx")
{
FormsAuthenticationTicket objTicket;
HttpCookie objCookie;
objTicket = new FormsAuthenticationTicket(1, txtUsername.Text,
DateTime.Now, DateTime.Now.AddMinutes(60), true,
"tt@server.com");
objCookie = new HttpCookie(".ASPXAUTH");
objCookie.Value = FormsAuthentication.Encrypt(objTicket);
Response.Cookies.Add(objCookie);

Response.Redirect("Default.aspx");
}
}

In the default.aspx Page_Load event add the following code..

void Page_Load() {
FormsIdentity objTicket;

objTicket = (FormsIdentity)User.Identity;
lblName.Text = objTicket.Ticket.Name;
lblIssueDate.Text = objTicket.Ticket.IssueDate.ToString();
lblExpiration.Text = objTicket.Ticket.Expiration.ToString();
lblIsPersistent.Text = objTicket.Ticket.IsPersistent.ToString();
lblVersion.Text = objTicket.Ticket.Version.ToString();
lblUserData.Text = objTicket.Ticket.UserData;
}

Enjoy coding..

No comments: