.Net Web Api - 覆盖授权过滤器

问题描述:

您好,我在一个mvc网站里面有一个web api控制器。 我试图允许使用2条规则访问控制器: 用户是管理员或请求来自本地计算机;.Net Web Api - 覆盖授权过滤器

我是新来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进行。我该怎么做?

此致 塔尔Humy

+1

“然后我用两个属性装饰我的控制器”我只看到一个... – spender

+0

对不起,我修好了 –

一种解决方案是创建从AuthorizeAttribute

例如继承的类像这样

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(角色= “支持,管理员”)]

在上面的代码,IdentityExtensions检查,和高速缓存, ActiveDirectory角色也允许我们通过更改缓存来伪造当前拥有角色的用户。