Latest Posts

Sunday, July 28, 2013

Forms Authentication

 void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    FormsIdentity formsIdentity = (FormsIdentity)HttpContext.Current.User.Identity;
                    string[] userRoles = formsIdentity.Ticket.UserData.Split(',');
                    HttpContext.Current.User = new GenericPrincipal(formsIdentity, userRoles);
                }
            }
        }
    }

 protected void Login_Click(object sender, EventArgs e)
    {
        FormsAuthenticationTicket formsAuthenticationTicket = new FormsAuthenticationTicket(1, "abcd", DateTime.Now, DateTime.Now.AddMinutes(30), false, "Admin");
        string encryptedFAT = FormsAuthentication.Encrypt(formsAuthenticationTicket);
        HttpCookie httpcookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedFAT);
        HttpContext.Current.Response.Cookies.Add(httpcookie);
        string returnURL = Request.QueryString["returnURL"];
        if (returnURL == null)
        {
            Response.Redirect(returnURL);
        }
        else
            Response.Redirect("Default.aspx");
    }

<authentication mode="Forms">
   <forms defaultUrl="Default.aspx" loginUrl="Login.aspx">
   </forms>
  </authentication>
  <authorization>
   <allow roles="Admin"/>
   <deny users="*"/>
  </authorization>