views:

851

answers:

4

I'm doing a custom authentication method that uses a light session object to hold a user's authorization details. Now I want each page (mainly child pages of masters) to be able to tell whether a user should have access to the page.

Should I create a page class and derive the child pages from that?

What's the best way for the application to know which roles have access to which page?

A: 

If you need much flexibility in authorization, you'd better go with a custom page class. Otherwise, Web.config should be enough.

Mehrdad Afshari
A: 

If you plug it with a custom role provider, you can actually rely on the asp.net configuration for this. There is a method that lets you check whether the user is authorized to access a given page:

System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal(
     "~/admin/test.aspx", principal, "GET"
);

You then get to use normal approach on web.config to configure authorization. When doing so, if the pages are in the same folder, you can just add a web.config to that folder and configure authorization appropriately.

eglasius
A: 

In same scenarios I put the pages that need authentication in a folder and I define location element in web.config to configure authentication like that :

<location path="protected">
     <system.web>
        <authorization>
          <deny users="?"/>
        </authorization>
    </system.web>
</location>
Canavar
A: 

I don't like the base page approach. To me it's too late for check the security stuff. You can create your own HttpModule to check that, either storing the authorization information in a database/xml/... or reading it using reflection on the page.

The context.Handler will hold the class Page you are executing. Thus you can do something like this:

I copy a part of the code I use, it checks roles, public pages, skips the check for images and scripts (but you could do it as well):

    // In the HttpModule:
 public void context_PreRequestHandlerExecute(object sender, EventArgs e)
 {
  HttpContext context = HttpContext.Current;

  // Don´t validate permissions if the user wasn´t allowed by the asp.net security
  // Neighter the advanced (custom) permissions are validated for non ASPX files.
  if (!context.Request.FilePath.EndsWith(".aspx") || !context.User.Identity.IsAuthenticated)
   return;

  // Give full access to the unathorized error page, and logins, and so on...
  string pageClass = context.Handler.GetType().BaseType.FullName;

  string param = context.Request["p"];
  if (!string.IsNullOrEmpty(param))
   pageClass += "@" + param;

  if (SecurityService.IsFullTrustClass(pageClass))
   return;

  if (SecurityService.Context.CurrentPerson == null)
  {
   LogOff();
   return;
  }

  // Verify access permissions for the current page
  IList<Role> roles = SecurityService.Context.CurrentPerson.Roles;
  bool allow = SecurityService.HasAccessPermission(pageClass, roles);

  if (!allow)
  {
   LogOff();
  }
 }
Diego Jancic