views:

36

answers:

2

Is there a way of listing which roles have access to a given page via code?

Example, I have a Testpage.aspx, and I wanted to list the roles allowed for this page when a user accesses the page. The URLAuthorizationManager must be able to find this out somehow, so there must be a way it knows what roles are configured in the webconfig for a page. or URL.

Here is the webconfig limiting the roles allowed to view this page.

<location path="Testpage.aspx">
    <system.web>
      <authorization>
        <allow roles ="admin,sales" />
      </authorization>
    </system.web>
  </location>

If I could find a solution, it would return "admin", "sales". Any one know how I can do this? Thanks

A: 

Use the Roles.GetAllRoles() method

http://msdn.microsoft.com/en-us/library/system.web.security.roles.getallroles.aspx

and here is an example where they list all roles: http://weblogs.asp.net/scottgu/archive/2005/10/18/427754.aspx

del.ave
This seems to list all available roles in the application -- not the roles that can access the page
Dan Esparza
You can also take a look at the ConfigurationLocation classhttp://msdn.microsoft.com/en-us/library/3dab5d1z.aspxThis class is used internally so you might want to keep digging with Reflector.
del.ave
+1  A: 

You can use the following code inside the page where you want to obtain the information.

var section = (AuthorizationSection)
    WebConfigurationManager.GetSection("system.web/authorization");
var rules = section.Rules;
var allowedRoles = rules
    .OfType<AuthorizationRule>()
    .Where(r => r.Action == AuthorizationRuleAction.Allow)
    .Select(r => r.Roles).First();

The reason for the call to First() is that .NET configuration is hierarchical. Suppose you have the following web site hierarchy and configuration:

/Default.aspx
/Web.config        (<allow roles="admin,user" />)
/SubDir/
       /Test.aspx
       /Web.config (<allow roles="admin,other" />)

and you call the code above from Test.aspx.cs, then the property AuthorizationSection.Rules contains three items corresponding to respectively the configuration from /SubDir/Web.config, Web.config and machine.config. So the first element contains the roles admin and other.

Ronald Wildenberg
Thanks Ronald. The explanation in your answer pointed me in the right direction and now I can enumerate all the roles for a given page.
Chris
Good to hear that. If this was (part of) the answer to your question, could you then mark it as answered? Thanks.
Ronald Wildenberg