如何以编程方式列出哪些 ASP.Net 角色可以访问页面?

发布于 2024-09-13 09:34:32 字数 486 浏览 6 评论 0原文

有没有一种方法可以通过代码列出哪些角色可以访问给定页面?

例如,我有一个 Testpage.aspx,我想列出当用户访问该页面时该页面允许的角色。 URLAuthorizationManager 必须能够以某种方式找到这一点,因此必须有一种方法它知道在页面的 webconfig 中配置了哪些角色。或网址。

这是限制允许查看此页面的角色的 Web 配置。

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

如果我能找到解决方案,它将返回“admin”、“sales”。有人知道我该怎么做吗?谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

青巷忧颜 2024-09-20 09:34:32

您可以在想要获取信息的页面中使用以下代码。

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();

调用 First() 的原因是 .NET 配置是分层的。假设您有以下网站层次结构和配置:

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

并且您从 Test.aspx.cs 调用上面的代码,然后属性 AuthorizationSection.Rules 包含分别对应的三个项来自 /SubDir/Web.configWeb.configmachine.config 的配置。因此第一个元素包含角色 adminother

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.

梦途 2024-09-20 09:34:32

我的问题非常相似,只是我需要能够迭代所有的
目录和相关子目录,并显示每个网页和文件夹目录允许的角色。我无法使用 Ronald Wildenberg 的解决方案,因为我们使用的是 .Net 2.0,所以我们没有 Linq 功能。

他的解决方案为我提供了所需的路线图。我还从 Microsoft 的法国 IIS 支持团队找到了帮助,以编程方式管理表单身份验证。我不想像他们发布的那样重写配置文件,而是我们需要能够显示应用程序中所有目录和页面允许的角色。我们的应用程序很小。它总共有 15 个目录和不到 100 个页面,因此运行速度相当快。您的里程可能会根据您网站的大小而有所不同。

我从根目录开始递归搜索所有 webconfig。我将它们及其路径添加到字符串列表中,然后迭代该列表并调用我的 ListRoles 函数。此函数打开 Web 配置并获取位置集合。然后它会像 Ronald 一样查找“system.web/authorization”。如果找到授权部分,它将循环遍历规则并排除任何继承的规则,并重点关注具有关联角色的 AuthorizationRuleAction.Allow:

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...
        }

    }
}

来自法国 IIS 支持团队博客

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;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文