Dave Gordon
Dave Gordon

Reputation: 1835

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?

Upvotes: 4

Views: 3124

Answers (2)

Shahid Awan
Shahid Awan

Reputation: 79

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>

Upvotes: 1

wazz
wazz

Reputation: 5068

look into using the/a web.config file and the authorization element. you can create a web.config file in any directory for this purpose (i.e., you can have several web.config files throughout the site).

one link (look into other links as well): https://msdn.microsoft.com/en-us/library/8d82143t%28v=vs.85%29.aspx

Upvotes: 2

Related Questions