How to Implement Forms Authentication Tickets

How to implement Forms authentication tickets and managing user roles based access in ASP.NET using C#

Configuring web.config file in application root

<authentication mode="Forms">

       <forms defaultUrl="Default.aspx" loginUrl="~/Login.aspx"

       slidingExpiration ="true" timeout="20"></forms>

</authentication>


Defining roles and accessibility in root web.config

<location path="HR">

       <system.web>

              <authorization>

                     <allow roles="HRADMIN"/>

                     <deny users="*"/>

              </authorization>

       </system.web>

</location>

Defining roles settings for folders and aspx within those folders in web.config file in those folders

<system.web>

       <authorization>

              <allow roles="ADMIN"/>

              <deny users="*"/>

       </authorization>

</system.web>


Settings for any logged in member

       <authorization>

              <deny users="?"/>

       </authorization>


Now after creating Login page we need to authenticate user

    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)

    {

        string userName = Login1.UserName;

        string password = Login1.Password;

        bool rememberUserName = Login1.RememberMeSet;

        if (AuthenticateUser(txtuser.text, txtPassword.text))

        {

            //Fetch the role

            string roles = "role";

            //Create Form Authentication ticket

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(

                1, userName, DateTime.Now, DateTime.Now.AddMinutes(20), rememberUserName, roles,

                FormsAuthentication.FormsCookiePath);

            // In the above parameters 1 is ticket version, username is the username associated with this ticket

            //time when ticket was issued , time when ticket will expire, remember username is user has chekced it

            //roles associted with the user, and path of cookie if any

            //For security reasons we may hash the cookies

            string hashCookies = FormsAuthentication.Encrypt(ticket);

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);

            // add the cookie to user browser

            Response.Cookies.Add(cookie);

            // get the requested page

            string returnUrl = Request.QueryString["ReturnUrl"];

            if (returnUrl == null)

                returnUrl = "~/Default.aspx";

            Response.Redirect(returnUrl);

        }

    }
Now to retrieve the authentication and roles information on every request we need to write this code in Global.asax file

    protected void Application_AuthenticateRequest(object sender, EventArgs e)

    {

        // look if any security information exists for this request

        if (HttpContext.Current.User != null)

        {

            // see if this user is authenticated, any authenticated cookie (ticket) exists for this user

            if (HttpContext.Current.User.Identity.IsAuthenticated)

            {

                // see if the authentication is done using FormsAuthentication

                if (HttpContext.Current.User.Identity is FormsIdentity)

                {

                    // Get the roles stored for this request from the ticket

                    // get the identity of the user

                    FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

                    //Get the form authentication ticket of the user

                    FormsAuthenticationTicket ticket = identity.Ticket;

                    //Get the roles stored as UserData into ticket

                    string[] roles = ticket.UserData.Split(',');

                    //Create general prrincipal and assign it to current request

                    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);

                }

            }

        }

    }
To check whether user in in the role or not we need to write this code in every page which provide access on role basis

    protected void Page_Load(object sender, EventArgs e)

    {

        if (HttpContext.Current.User.IsInRole("HRADMIN "))

        {

            lblMessage.Text = "Welcome HR Administrator";

        }

    }


Mr. Ravi Krishna - Senior Software Engineer
I am a Mocrosoft ASP.net Developer and MCP Certified professional. I have overall 5 years of experience in IT Industry,in that 3 years experience in Microsoft BI(SSAS,SSIS,SSRS). I have experience on various business domains like Automation and Chemical.
https://sites.google.com/site/rkkumardotnet/
Read moreRead more about Contributor