Custom authorization attribute not working in WebAPI

故事扮演 提交于 2019-11-29 16:26:52

问题


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

Above is my CustomAuthorizeAttribute Class and

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

When I'm calling

http://localhost:1142/api/Profile 

It is not firing CustomAuthorizeAttribute

More over My FilterConfig class is look like below

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

Please help if I miss something.


回答1:


  1. Looks like you are using an MVC filter instead of a Web API filter. It can be detected in the sample because it uses HttpContextBase. Instead use the filter from the System.Web.Http.Filters namespace.
  2. You need to override OnAuthorization or OnAuthorizationAsync on the Web API filter.
  3. You don't need to register a global filter and decorate your controller with it. Registering it will make it run for all controllers.

Web API filter code: https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Http/Filters/AuthorizationFilterAttribute.cs




回答2:


YOur custom attribute should inherit from System.Web.Http.Filters.AuthorizationFilterAttribute

and it should look like this

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);
    }
}



回答3:


Try with this.

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



回答4:


To add onto the other answers that have you inherit from System.Web.Http.Filters.AuthorizationFilterAttribute, I put this into my OnAuthorization method to make sure the user was logged in:

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");
} 


来源:https://stackoverflow.com/questions/23339002/custom-authorization-attribute-not-working-in-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!