Search code examples
c#asp.netwebformsauthorizationauthorize-attribute

ASP.NET WebForms - How to Authorise access to a page


In the latest ASP.NET WebForms application we no longer user RoleManager etc (as far as I can tell) so how do we authorize access to a webpage for a particular role?

In MVC I would use the Authorize attribute but that doesn't exist in WebForms so I am at a loss - any ideas?


Solution

  • try this code on login to pass role to FormsAuthenticationTicket

    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, UserName.Text, DateTime.Now, DateTime.Now.AddMinutes(2880), 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);
                Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text, false));
    

    on particular webform on Page_Load event retrieve role

    protected void Page_Load(object sender, EventArgs e)
        {
    
                 FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                 FormsAuthenticationTicket ticket = id.Ticket;
                 string userData = ticket.UserData;
                 string[] temp = userData.Split(',');
                 role=temp[0];
             if (role!="Owner")
             {
                 Response.Write("............");
             }
        }
    

    if you want authorization on folder level then instead of checking role on webform specify role in web.config file of that folder

     <authorization>
      <allow  roles="Owner"/>
      <deny users="*"/>
    </authorization>