ASP.NET Location Based Authorization

When using ASP.NET forms authentication it is easy to restrict users from accessing pages in certain folders. I usually add a Web.Config file containing the Authorization block to each folder. If we wanted to allow the Admin role in a folder and deny everything else, we could use the following:

<configuration>
  <system.web>
    <authorization>
      <allow roles="Admin" />
      <deny users="*" />
      <deny users="?" />
    </authorization>
  </system.web>
</configuration>

This is the entire Web.Config file for that folder. Providing you have a Web.Config in the root, you don’t need to repeat other elements here. Configuration files inherit elements from configuration files in parent folders.

Applying these settings on an entire folder may not always suit your needs. You can have the same control at a page level by using the Location element:

<configuration>
  <location path="AdminPage.aspx">
    <system.web>
      <authorization>
        <allow roles="Admin" />
        <deny users="*" />
        <deny users="?" />
      </authorization>
    </system.web>
  </location>
</configuration>

If the folder contains several pages, only AdminPage.aspx is restricted.

Advertisements
This entry was posted in Tips and Tricks and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s