首页 文章

是否可以在web.config中基于每个控制器设置用户授权? (不能使用AuthorizeAttribute)

提问于
浏览
2

我有一个使用Windows身份验证的Web API 2应用程序 . 我有多个控制器,这在我的web.config中用于授权:

<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>

这个"blanket"授权很有效, 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 .

显而易见的答案是在控制器类上使用 [Authorize()] 属性,但我不能使用此属性,因为我使用per-environment(Dev-UAT-Prod)XML转换为web.config并且需要能够更改用户在每个环境中都有权使用这些控制器 .

那么,是否可以在我的web.config文件中为各个控制器指定授权?

我对其他解决方案持开放态度,只要它们允许在每个环境(dev-uat-prod)中部署应用程序时授权不同的用户 .

谢谢!

1 回答

  • 2

    在我们的环境中我们使用这种方法:

    Active Directory组的名称存储在app-settings中 . 这些名称因环境而异 .

    接下来我们创建了一个 AuthorizeAttribute 的子类型,名为 AuthorizeWritersAttribute ,如下所示:

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

    最后,我们将此属性应用于控制器:

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

    我们使用AD组,但AD帐户也可以使用 .

相关问题