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

时间:2013-12-11 12:35:14

标签: .net asp.net-web-api

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

我正在寻找类似的东西:

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
    }

}

2 个答案:

答案 0 :(得分:2)

我已通过向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);
    }
}

答案 1 :(得分:1)

将此添加到global.asax文件中的api配置方法:

    private static void ConfigureApis(HttpConfiguration config)
    {
        //create AuthorizeAttribute from System.Web.Http
        var auth = new AuthorizeAttribute { Roles = "Admin" };
        //add it to webapi configuration
        config.Filters.Add(auth);
    }