1

I was setting up permissions for pages in a ASP.NET website with <location> tags in web.config, something similar to this:

<location path="Users.aspx">
  <system.web>
    <authorization>
      <allow roles="Administrator"/>
      <deny users="*"/>
    </authorization>
  </system.web>
</location>

However, I also have a web.sitemap which basically contains the same information, i.e. which user roles can see/access which pages. A snippet from my web.sitemap:

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
  <siteMapNode title="Home">
    ... lots of nodes here ...
    <siteMapNode url="users.aspx" roles="Administrator" title="users" description="Edit users" />
    ...
  </siteMapNode>
</siteMap>

Is there some kind of nifty way of using web.sitemap only to configure access? The <location> tags are quite verbose, and I don't like having to duplicate this information.

4

3 回答 3

1

可能您正在寻找SecurityTrimmingEnabled。有关更多详细信息,请参阅此论坛帖子博客条目

因此Web.config限制了直接输入 URL 和Web.sitemap显示的 URL 的访问

于 2010-04-01T08:59:22.847 回答
0

当然,您可以在 web.config 中定义 SiteMapProvider,并使用 CurrentNode 属性来获取与请求页面相关的 SiteMapNode。

首先声明您的站点地图提供者(web.config):

<siteMap enabled="true" defaultProvider="DefaultXmlSiteMapProvider">
  <providers>
    <add siteMapFile="Web.sitemap" name="DefaultXmlSiteMapProvider" securityTrimmingEnabled="true" type="System.Web.XmlSiteMapProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
  </providers>
</siteMap>

使用 CurrentNode 进行页面访问控制的示例代码(您可以做得更好;)):

bool hasAccess = false;

if (SiteMap.CurrentNode == null)
    throw new ApplicationException("Page not present in SiteMap : " + this.Request.Url.AbsolutePath);

if (SiteMap.CurrentNode.Roles.Count > 0)
{
    // All roles or no roles
    if (SiteMap.CurrentNode.Roles.Contains("*") == true)
    {
        hasAccess = true;
    }
    else
    {
        for (int index = 0; index < SiteMap.CurrentNode.Roles.Count; index++)
        { 
            string role = SiteMap.CurrentNode.Roles[index].ToString();
            hasAccess = HttpContext.Current.User.IsInRole(role);
            if (hasAccess == true)
               break;
        }
    }
}

注意我添加了所有人角色(*),非常有用。

于 2010-04-01T09:26:13.317 回答
0

这是我自己的代码,SiteMapProvider它抛出一个异常,用户被请求一个页面(节点)无权这样做(他的角色不在节点的角色列表中)

public class XmlSiteMapProvider : System.Web.XmlSiteMapProvider
{
    public override bool IsAccessibleToUser(HttpContext context, SiteMapNode node)
    {
        var roles = node.Roles.OfType<string>();
        if (roles.Contains("*") || (roles.Count(r => context.User.IsInRole(r)) > 0))
        {
            return true;
        }
        else
        {
            throw new InsufficientRightsException();
        }
    }
}

为了实现我自己的角色逻辑,我也制作了自己的RoleProvider.

于 2010-06-30T07:15:00.710 回答