Role Based Forms Authentication in ASP.Net


.aspx

<asp:TextBox ID="Username" runat="server" CssClass="input" TabIndex="1"></asp:TextBox>
<asp:TextBox ID="Password" runat="server" CssClass="input" TabIndex="2" TextMode="Password"></asp:TextBox>

.aspx.cs

using System.Web.Security;

FormsAuthentication.Initialize();
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, User, DateTime.Now, DateTime.Now.AddMinutes(30), false, Role, FormsAuthentication.FormsCookiePath);
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
            Response.Cookies.Add(cookie);
            string returnURL = Request.QueryString["ReturnUrl"];
            if (returnURL == null)
            {
                if (Role == "Admin")
                {
                    returnURL = "~/Admin/Home.aspx";
                }
                else
                {
                    returnURL = "~/User/Home.aspx";
                }
                Response.Redirect(returnURL);

Root Config

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="Forms">
      <forms name=".ASPXFORMSAUTH" loginUrl="~/Login.aspx" cookieless="UseCookies" defaultUrl="~/Login.aspx" timeout="30" protection="All" path="/" slidingExpiration="false"></forms>
    </authentication>
    <authorization>
      <allow users="*"/>
    </authorization>
  </system.web>

Sub(Folder) Config

    <system.web>
      <authorization>
        <!-- Order and case are important below -->
        <allow roles="Admin,User"/>
        <deny users="*"/>
        <!--If you dont wish role based then use anonymous(?)-->
        <!--<deny users="?"/>-->
      </authorization>
    </system.web>

Access Forms Authentication Ticket Data

HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
            lblusername.Text = ticket.Name;

You Can Download the Working Code From here.