以编程方式检查页面是否需要基于web.config设置进行身份验证

时间:2011-12-29 00:42:45

标签: c# asp.net web-config forms-authentication

我想知道是否有办法检查页面是否需要基于web.config设置进行身份验证。基本上如果有这样的节点

  <location path="account">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>

然后我想检查任何页面是否需要身份验证,如果它在帐户目录下,则返回true。这可能吗?

3 个答案:

答案 0 :(得分:7)

解决方案是创建匿名身份(主体),并将其传递给CheckUrlAccessForPrincipal方法。它将确定页面是公开的还是需要身份验证。

见下面的代码:

var principal = new GenericPrincipal(new GenericIdentity(String.Empty, String.Empty), new string[]{});
bool requiredAuthentication = UrlAuthorizationModule.CheckUrlAccessForPrincipal(Page.AppRelativeVirtualPath, principal, Request.HttpMethod);

答案 1 :(得分:4)

您是否在检查用户请求的页面?它不太可能,因为请求永远不会到达页面。检查网址授权工作流程。

enter image description here

http://www.asp.net/web-forms/tutorials/security/membership/user-based-authorization-cs

答案 2 :(得分:0)

我对你的确切要求感到有点困惑,但是要使用你的web.config来逐页强制执行身份验证,你需要这样的东西:

 <location path="Forms/Administration/Default.aspx">
        <system.web>
            <authorization>
                <allow roles="Administrator, User, AdditionalUser" />
            </authorization>
        </system.web>
    </location>

如果您需要更细粒度,则需要将逻辑添加到中间层,然后检查页面加载或URL请求(如果是MVC)。