gpt4 book ai didi

.net - 默认情况下如何拒绝对 Web API 项目的授权

转载 作者:行者123 更新时间:2023-12-04 20:44:29 25 4
gpt4 key购买 nike

除非明确允许授权,否则是否可以拒绝对项目中每个 ASP.NET Web API Controller 的授权(甚至对于经过身份验证的用户)?

我正在寻找类似的东西:

WebApiConfig

config.Filters.Add(new DenyAuthorizationAttribute());   // ??

ExampleController.cs
public class ExampleController : ApiController
{
[Authorize(Roles = "Admins")]
public string GetHello_OnlyAdmins()
{
// only admins can call this
}

[AllowAnonymous]
public void PostSomething_Everybody()
{
// ...
}

public void DeleteSomething_NoOne()
{
// nobody can call this - we want to force the programmer to be specific about authorized roles
}

}

最佳答案

我通过向 HttpConfiguration.Filters 添加自定义“默认拒绝”授权过滤器解决了这个问题。 :

public class DefaultDenyAuthorizationFilter : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if ( null == actionContext )
throw new ArgumentNullException("actionContext");

if ( actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any() ||
actionContext.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>().Any() ||
actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any() ||
actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AuthorizeAttribute>().Any() )
return;

base.HandleUnauthorizedRequest(actionContext);
}
}

关于.net - 默认情况下如何拒绝对 Web API 项目的授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20519297/

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