Rush Frisby
Rush Frisby

Reputation: 11454

Programmatically check if page requires authentication based on web.config settings

I would like to know if there is a way to check if a page requies authentication based on the web.config settings. Basically if there is a node like this

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

then I would like to check on any page if it requires authentication or not and to return true if it is under the account directory. Is this possible?

Upvotes: 4

Views: 3354

Answers (3)

Rush Frisby
Rush Frisby

Reputation: 11454

The solution is to create an anonymous identity (principal), and pass it into the CheckUrlAccessForPrincipal method. It will determine if the page is public, or requires authentication.

See code below:

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

Upvotes: 7

Matt Cashatt
Matt Cashatt

Reputation: 24208

I am a little confused as to what you are asking exactly, but to use your web.config to enforce authentication on a page-for-page basis, you need something like this:

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

If you need to be more granular than that, you need to add the logic to your middle-tier and then check on page load or url request (if MVC).

Upvotes: 0

benni_mac_b
benni_mac_b

Reputation: 8877

Are you checking the page that the user has requested? Its unlikely as the request will never get to the page. Check the url authorization workflow.

enter image description here

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

Upvotes: 4

Related Questions