gpt4 book ai didi

c# - .Net Web Api - 覆盖 AuthorizationFilter

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:52 25 4
gpt4 key购买 nike

您好,我在 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 角色,这也允许我们通过更改缓存来伪造具有角色的当前用户。

关于c# - .Net Web Api - 覆盖 AuthorizationFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31536785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com