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
Start by creating a new folder in the project named Roles. Next, add four new ASP.NET pages to the Roles folder, linking each page with the Site.master master page. Name the pages: At this point your project's Solution Explorer should look similar to the screen shot shown in Figure 1.
The RolePrincipal class uses the Roles API to determine what roles the user belongs to. Figure 1 depicts the ASP.NET pipeline workflow when using forms authentication and the Roles framework. The FormsAuthenticationModule executes first, identifies the user via her authentication ticket, and creates a new GenericPrincipal object.
ASP.NET offers a Roles framework for defining roles and associating them with user accounts. With the Roles framework we can create and delete roles, add users to or remove users from a role, determine the set of users that belong to a particular role, and tell whether a user belongs to a particular role.
Role-based authorization in ASP.NET Core. When an identity is created it may belong to one or more roles. For example, Tracy may belong to the Administrator and User roles whilst Scott may only belong to the User role. How these roles are created and managed depends on the backing store of the authorization process.
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
.
My problem was very similar except I needed the ability to iterate through all of the directories and related subdirectories and display allowed roles for each web page and folder directory. I was unable to use Ronald Wildenberg's solution because we're using .Net 2.0 so we don't have the Linq functionality.
His solution gave me the roadmap I needed. I also found help from from Microsoft's French IIS Support Team, Managing Forms Authentication Programmatically. I didn't want to rewrite the config files like they posted, rather we needed the ability to show the allowed roles for all directories and pages in our application. Our application is small. It has a total of 15 directories and less than 100 pages so this runs pretty quickly. Your mileage my vary depending on the size of your web site.
I started from the root directory and recursively searched for all webconfigs. I added them with their path to a string list then iterated through the list and called my ListRoles function. This function opens the web config and gets the location collection. Then it looks for the "system.web/authorization" like Ronald did. If it finds an authorization section it loops through the rules and excludes any inherited rules and focuses on AuthorizationRuleAction.Allow with associated roles:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web.Configuration;
public void DisplayWebPageRoles()
{
//First walk the directories and find folders with Web.config files.
//Start at the root
DirectoryInfo baseDir = new DirectoryInfo(Server.MapPath("~/"));
//Do a little recursion to find Web.Configs search directory and subdirs
List<string> dirs = DirectoriesWithWebConfigFile(baseDir);
//Replace the folder path separator except for the baseDir
for (int i = 0; i < dirs.Count; i++)
{
dirs[i] = dirs[i].Replace(
baseDir.FullName.Replace("\\", "/"),
"/" + baseDir.Name + (i > 0 ? "/" : ""));
}
//Now that we have the directories, we open the Web.configs we
//found and find allowed roles for locations and web pages.
for (int i = 0; i < dirs.Count; i++)
{
//Display on page, save to DB, etc...
ListRoles(dirs[i]);
}
}
public List<string> DirectoriesWithWebConfigFile(DirectoryInfo directory)
{
List<string> dirs = new List<string>();
foreach (FileInfo file in directory.GetFiles("Web.config"))
{
dirs.Add(directory.FullName.Replace("\\","/"));
}
foreach (DirectoryInfo dir in directory.GetDirectories())
{
dirs.AddRange(DirectoriesWithWebConfigFile(dir));
}
return dirs;
}
private void ListRoles(string configFilePath)
{
System.Configuration.Configuration configuration =
WebConfigurationManager.OpenWebConfiguration(configFilePath);
//Get location entries in web.config file
ConfigurationLocationCollection locCollection = configuration.Locations;
string locPath = string.Empty;
foreach (ConfigurationLocation loc in locCollection)
{
try
{
Configuration config = loc.OpenConfiguration();
//Get the location path so we know if the allowed roles are
//assigned to a folder location or a web page.
locPath = loc.Path;
if (locPath.EndsWith(".js")) //Exclude Javascript libraries
{
continue;
}
AuthorizationSection authSection =
(AuthorizationSection)config
.GetSection("system.web/authorization");
if (authSection != null)
{
foreach (AuthorizationRule ar in authSection.Rules)
{
if (IsRuleInherited(ar))
{
continue;
}
if (ar.Action == AuthorizationRuleAction.Allow
&& ar.Roles != null
&& ar.Roles.Count > 0)
{
for (int x = 0; x < ar.Roles.Count; x++)
{
//Display on page, save to DB, etc...
//Testing
//Response.Write(
// configFilePath + "/web.config" + ","
// + configFilePath + "/" + locPath + ","
// + ar.Roles[x] + "<br />");
}
}
}
}
}
catch (Exception ex)
{
//Your Error Handling Code...
}
}
}
From French IIS support Team blog
private bool IsRuleInherited(AuthorizationRule rule)
{
//to see if an access rule is inherited from the web.config above
//the current one in the hierarchy, we look at two PropertyInformation
//objects - one corresponding to roles and one corresponding to
//users
PropertyInformation usersProperty = rule.ElementInformation.Properties["users"];
PropertyInformation rolesProperty = rule.ElementInformation.Properties["roles"];
//only one of these properties will be non null. If the property
//is equal to PropertyValueOrigin.Inherited, the this access rule
//if not returned in this web.config
if (usersProperty != null)
{
if (usersProperty.ValueOrigin == PropertyValueOrigin.Inherited)
return true;
}
if (rolesProperty != null)
{
if (rolesProperty.ValueOrigin == PropertyValueOrigin.Inherited)
return true;
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With