AKanyer AKanyer - 1 year ago 150
ASP.NET (C#) Question

Can user authorization be set on a per-controller basis in web.config? (cannot use AuthorizeAttribute)

I have a Web API 2 app using windows auth. I have multiple controllers and this in my web.config for authorization:

<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Windows" />
<allow users="AllowedUsersAndGroups" />
<deny users="?" />
<sessionState mode="Off" />

This "blanket" authorization works great, but I have 2 specific controllers that I need to lock down differently: I want to specify different users that are authorized to hit these 2 controllers.

The obvious answer would be to use the
attribute on the controller classes, however I cannot use this attribute because I am using per-environment (Dev-UAT-Prod) XML transforms to the web.config and need to be able to change which users are authorized on these controllers in each environment.

So, is it possible to specify authorization for individual controllers in my web.config file?

I am open to other solutions as long as they allow for Authorizing different users when the app is deployed in each environment (dev-uat-prod).


Answer Source

In our environment we use this approach:

The names of Active Directory groups are stored in the app-settings. These names are different per environment.

Next we created a subtype of AuthorizeAttribute called AuthorizeWritersAttribute like this:

public class AuthorizeWritersAttribute : AuthorizeAttribute 
    public AuthorizeWritersAttribute()
        Roles = ConfigurationManager.AppSettings["SolutionName:AuthorizedWriters"];
        // Actually we removed the dependency on ConfigurationManager but for brevity this suffices.

Finally we apply this attribute to our controllers:

public class BlogController : Controller

We use AD-groups but AD-accounts should work as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download