Tuesday, December 20, 2011

Forms Authentication - Creating the Forms Authentication Cookie

We can explicitly create the Authentication Cookie in Forms Authentication mode. using below code.

E.g.

protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
{
if (Membership.ValidateUser(LoginUser.UserName, LoginUser.Password))
{
if (Request.QueryString["ReturnUrl"] != null)
{
FormsAuthentication.RedirectFromLoginPage(LoginUser.UserName,false);
}
else
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
LoginUser.UserName,
DateTime.Now,
DateTime.Now.AddMinutes(30), // value of time out property
false, // Value of IsPersistent property
String.Empty,
FormsAuthentication.FormsCookiePath);

string encryptedTicket = FormsAuthentication.Encrypt(ticket);

HttpCookie authCookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
encryptedTicket);

Response.Cookies.Add(authCookie);

Response.Redirect("~/Default.aspx", false);
}

}
else
{
e.Authenticated = false;
}
}

No comments:

Post a Comment