Skip to main content
 首页 » 编程设计

c#之.Net Web Api之覆盖 AuthorizationFilter

2024年06月03日43cyq1162

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

我是 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 个属性装饰我的 Controller

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

但正如我所怀疑的,现在,为了访问 Controller ,我需要成为管理员并且应该从本地主机发出请求。我该怎么做?

亲切的问候, 塔尔休米

请您参考如下方法:

一个解决方案是创建一个继承自 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(Roles = "Support,Admin")]

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