R – In the codebehind class, how to retrieve the authorized roles

asp.netrolesweb.config

I have the following in my web.config:

<location path="RestrictedPage.aspx">
    <system.web>
        <authorization>
            <allow roles="Group1Admin, Group3Admin, Group7Admin"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>

Within RestrictedPage.aspx.cs, how do I retrieve the allowed roles collection that contains Group1Admin, Group3Admin, and Group7Admin?

Here's why I ask:

The web.config is handling the authorization to the page. That works fine. But I'm going to have a couple of these pages (say RestrictedPage.aspx, RestrictedPage2.aspx, RestrictedPage3.aspx). Each of these pages is going to have my custom webcontrol on it. And each of these pages will have different allowed roles. My webcontrol has a dropdown list. The choices within the dropdown depend on the intersection of the user's roles and the page's allowed roles.

As mentioned below, searching the web.config with XPath would probably work. I was just hoping for something more framework-y. Kind of like SiteMap. When I put roles in my web.sitemap, I can grab them using SiteMap.CurrentNode.Roles (my website is using Windows authentication, so I can't use web.sitemap for security trimming and I'd rather maintain roles in only one file).

Best Answer

// set the configuration path to your config file
string configPath = "??";

Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);

// Get the object related to the <identity> section.
AuthorizationSection section = (AuthorizationSection)config.GetSection("system.web/authorization");

from the section object get the AuthorizationRuleCollection object where you can then extract the Roles.

Note: You'll probably need to modify the path to the section a bit since you start with "location path="RestrictedPage.aspx"", I didn't try that scenario.

Related Topic