【问题标题】:Allow Roles for Users in WebApi2 using IIS Basic Authentication with Authorize Attribute使用带有授权属性的 IIS 基本身份验证允许 WebApi2 中的用户角色
【发布时间】:2014-06-04 23:05:18
【问题描述】:

我有一个 .net WebApi2 项目。我正在使用提供基本身份验证的 IIS。

有 2 个客户端需要访问此 Web 服务,并且有 2 个控制器。控制器 #1 = EmployeeController 和控制器 #2 = InvoiceController 我有一个列出用户名和角色的数据库。 Role1 = EmployeeUsers 和 Role2 = InvoiceUsers。

我想使用这样的授权属性...

[Authorize(Roles = "EmployeeUsers ")]
public class EmployeeController : ApiController
{

}

和

[Authorize(Roles = "InvoiceUsers")]
public class InvoiceController : ApiController
{

}

如果没有授权属性,我可以通过 Request.GetRequestContext().Principal 访问经过身份验证的用户,但我只能在用户通过身份验证并允许访问控制器后才能访问。

我希望能够获取经过身份验证的基本用户信息(请记住,IIS 正在处理基本身份验证)并使用 [Authorize] 属性允许基于用户可能处于的某些角色访问控制器...但是在什么时候我可以访问经过身份验证的用户(委托人),检查他的角色,并允许 [Authorize] 属性完成其工作或允许或拒绝访问某些控制器?

仅供参考...必须使用 IIS 来处理基本身份验证...因此在 IIS 中设置了基本身份验证,而我的 web.config 设置了身份验证模式=“Windows”。

如何使用 Authorize 属性根据通过 IIS 身份验证的用户来限制对控制器的访问?

【问题讨论】:

    标签: c# authentication asp.net-web-api asp.net-web-api2


    【解决方案1】:

    我没有太多使用 IIS 进行身份验证的经验,but you can create your own attribute that inherits from AuthorizeAttribute,所以你可以自己动手:

    public class MyAuthorizationAttribute : AuthorizeAttribute
        {
            public override void OnAuthorization(HttpActionContext actionContext)
            {
                var principal = actionContext.Request.GetRequestContext().Principal;
                if (!principal.IsInRole(this.Roles))
                {
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                }
            }
        }
    

    然后你会用[MyAuthorizationAttribute(Roles = "Foo")]装饰你的控制器

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 2015-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 2019-10-04
      • 2013-05-17
      相关资源
      最近更新 更多