Monday, May 6, 2013

Form Authentication with Cookie in asp.net


private void Submit1_Click (object sender, System.EventArgs e)
{
     
    if(this.TextBox_username.Text.Trim()== "HR_manager"
        && this.TextBox_password.Text.Trim() == "password")    
    {
         // Success, create non-persistent authentication cookie.
         FormsAuthentication.SetAuthCookie(
                 this.TextBox_username.Text.Trim(), flase);
     
         FormsAuthenticationTicket ticket1 =
            new FormsAuthenticationTicket(
                 1,                                   // version
                 this.TextBox_username.Text.Trim(),   // get username  from the form
                 DateTime.Now,                        // issue time is now
                 DateTime.Now.AddMinutes(10),         // expires in 10 minutes
                 false,      // cookie is not persistent
                 "HR"                              // role assignment is stored
                 // in userData
                 );
          HttpCookie cookie1 = new HttpCookie(
            FormsAuthentication.FormsCookieName,
            FormsAuthentication.Encrypt(ticket1) );
          Response.Cookies.Add(cookie1);

          // 4. Do the redirect.
          String returnUrl1;
                 // the login is successful
          if (Request.QueryString["ReturnUrl"] == null)
          {
              returnUrl1 = "HRpages/HR_main.aspx";
          }
       
          //login not unsuccessful
          else
          {
              returnUrl1 = Request.QueryString["ReturnUrl"];
          }
          Response.Redirect(returnUrl1);
    }
}