How to white list a single controller or action when web.config restricts entire application by role by default?

737 views Asked by At

By default in my application, I have denied all users who are not in a particular active directory group, which works correctly.

Here is the snippet of the relevant part of my web.config.

<system.web>
    <authentication mode="Windows" />
    <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
    <authorization>
      <allow roles="domainXXX\GroupXXX" />
      <deny users="*" />
    </authorization>
    <identity impersonate="true" />
    <customErrors mode="RemoteOnly" defaultRedirect="~/Error">
      <error statusCode="401" redirect="~/Error/Unauthorised" />
    </customErrors>
  </system.web>

Now I would like the actions in a single controller to be accessible without authorisation. I have tried to add the [AllowAnonymous] attribute to my controller, but I still must be logged in to access these actions. Is it not possible to mix these approaches? i.e. restrict role in web.config and allow anonymous users via the [AllowAnonymous] attribute in a controller?

2

There are 2 answers

0
David Spence On BEST ANSWER

I went with this. Instead of restricting the role globally in web.config, the [AuthorizeAttribute] is now applied to all routes via in FilterConfig.cs. When added like this in code (and not in config) then the [AllowAnonymous] attribute seems to work as expected and allow authenticated access when it is annotated over a controller or action.

FilterConfig.cs

var authorizeAttribute = new AuthorizeAttribute
{
    Roles = "domainXXX\GroupXXX"
};

filters.Add(authorizeAttribute);

This allows control at the controller level rather than having to hard code URIs. So the URI of a controller can change and the attribute will still work as expected. In this was configured in web.config, you would have to remember to change the URI there.

Blogged here: http://spencerooni.github.io/2015/07/12/authenticating-and-authorizing-users-from-active-directory-in-asp.net.html

1
Shashank Chaturvedi On

This used to work well with webforms but never tested the same with MVC but I believe it should work:

<location path="~/xyzPage">
 <system.web>
  <authorization>
   <allow users="*"/>
  </authorization>
 </system.web>
</location>

Setting a separate authorization rule for a particular web location should work for you.

Hope this helps.