Custom authorization attribute not working in WebAPI

前端 未结 4 630
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 12:33
 public class CustomAuthorizeAttribute : AuthorizationFilterAttribute
 {  
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
       return         


        
相关标签:
4条回答
  • 2021-01-01 13:00

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-01 13:10
    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://github.com/aspnetwebstack/aspnetwebstack/blob/master/src/System.Web.Http/Filters/AuthorizationFilterAttribute.cs

    0 讨论(0)
  • 2021-01-01 13:22

    Try with this.

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            return true;
        }
    }
    
    0 讨论(0)
  • 2021-01-01 13:24

    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");
    } 
    
    0 讨论(0)
提交回复
热议问题