.Net Web Api - 覆盖AuthorizationFilter

时间:2015-07-21 10:40:33

标签: c# asp.net asp.net-mvc asp.net-web-api

您好我在mvc网站内有一个web api控制器。 我尝试使用2条规则允许访问控制器: 用户是管理员或请求来自本地计算机;

我是AuthorizationFilterAttribute的新手,但我尝试编写一个限制访问权限 仅限本地请求:

public class WebApiLocalRequestAuthorizationFilter : AuthorizationFilterAttribute
{

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }
        if (actionContext.Request.IsLocal())
        {
            return;
        }
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
        actionContext.Response.Content = new StringContent("Username and password are missings or invalid");
    }
}

然后我用2个属性

装饰我的控制器
[Authorize(Roles = "Admin")]
[WebApiLocalRequestAuthorizationFilter]
public class ContactController : ApiController
{
    public ContactModel Get(int id)
    {
        ContactsService contactsService = new ContactsService();
        return contactsService.GetContactById(id).Map<ContactModel>();
    }

}

但正如我所怀疑的,现在,为了访问控制器,我需要成为管理员,并且请求应该来自localhost。我该怎么办?

亲切的问候, Tal Humy

1 个答案:

答案 0 :(得分:3)

一种解决方案是创建一个继承自AuthorizeAttribute

的类

e.g。像这样的东西

public class MyAuthorizeAttribute: AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool accessAllowed = false;
        bool isInGroup = false;

        List<string> roleValues = Roles.Split(',').Select(rValue => rValue.Trim().ToUpper()).ToList();

        foreach (string role in roleValues)
        {
            isInGroup = IdentityExtensions.UserHasRole(httpContext.User.Identity, role);
            if (isInGroup)
            {
                accessAllowed = true;
                break;
            }
        }

        //add any other validation here
        //if (actionContext.Request.IsLocal()) accessAllowed = true;

        if (!accessAllowed)
        {
            //do some logging
        }

        return accessAllowed;
    }
...
}

然后你可以像这样使用它:

[MyAuthorizeAttribute(Roles =&#34; Support,Admin&#34;)]

在上面的代码中,IdentityExtensions检查并缓存ActiveDirectory角色,这些角色还允许我们通过更改缓存来伪造当前具有角色的用户。