自定义授权属性在WebAPI中无法工作

24
 public class CustomAuthorizeAttribute : AuthorizationFilterAttribute
 {  
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
       return true;// if my current user is authorised
    }
 }

以上是我的CustomAuthorizeAttribute类

[CustomAuthorize] // both [CustomAuthorize] and [CustomAuthorizeAttribute ] I tried 
public class ProfileController : ApiController
{
   //My Code..
}

我打电话时

http://localhost:1142/api/Profile 

它没有触发 CustomAuthorizeAttribute

而且我的FilterConfig类如下所示

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {            
        filters.Add(new CustomAuthorizeAttribute());
    }
}

如果我漏掉了什么,请帮忙指出。

4个回答

24
  1. 看起来您正在使用MVC过滤器而不是Web API过滤器。可以通过样例检测到,因为它使用 HttpContextBase。请改用System.Web.Http.Filters 命名空间中的过滤器。
  2. 您需要在Web API过滤器上重写OnAuthorization 或者 OnAuthorizationAsync方法。
  3. 您无需注册全局过滤器并将其装饰到控制器上。如果注册了全局过滤器,它将运行所有控制器。

Web API过滤器代码: https://github.com/aspnetwebstack/aspnetwebstack/blob/master/src/System.Web.Http/Filters/AuthorizationFilterAttribute.cs


@ChaoticCoder 看起来链接已经被修复了(https://stackoverflow.com/revisions/23344743/4)。 - ruffin

13

您的自定义属性应该继承自 System.Web.Http.Filters.AuthorizationFilterAttribute

并且它应该长成这个样子

using System.Web.Http.Controllers;
using System.Web.Http.Filters;
public class CustomAuthorizeAttribute : System.Web.Http.Filters.AuthorizationFilterAttribute
{   
    public override bool AllowMultiple
    {
        get { return false; }
    }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        //Perform your logic here
        base.OnAuthorization(actionContext);
    }
}

11

试试这个。

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        return true;
    }
}

谢谢,但我遇到了构建错误,像是没有适合重写的方法(实际上在AuthorizeAttribute中没有这样的方法):( - b_in_U
4
这个属性来自于System.Web.Http。如果你正在使用System.Web.Mvc属性,你应该重写AuthorizeCore方法! - leskovar
这就是你实际需要的东西。只需简单地提供一个布尔值,表示用户是否已被授权。 - Maarten Kieft

1
为了补充其他回答,您需要继承自System.Web.Http.Filters.AuthorizationFilterAttribute,我将以下内容添加到我的OnAuthorization方法中,以确保用户已登录:
if (!actionContext.RequestContext.Principal.Identity.IsAuthenticated)
{
     // or whatever sort you want to do to end the execution of the request
     throw new HttpException(403, "Forbidden");
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接