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

限于喜欢 提交于 2019-12-20 02:54:18

问题


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

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

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 [Authorize()] 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).

Thanks!


回答1:


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:

[AuthorizeWriters]
public class BlogController : Controller
{
    ....
}

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



来源:https://stackoverflow.com/questions/32871893/can-user-authorization-be-set-on-a-per-controller-basis-in-web-config-cannot-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!