1

Looking at a custom AuthorizeAttribute , I already know that the right method for checking authorization is the IsAuthorized method :

For example :

protected override bool IsAuthorized(HttpActionContext actionContext)
{
    bool isAuthroized = base.IsAuthorized(actionContext);
    return isAuthroized  && MY_OTHER_CONDITIONs; //!
}

Like I said I already know that.

But let's say I've decided to override OnAuthorization :

Here is an example code from an existing library:

public class CustomerOrdersAuthorizeAttribute : AuthorizeAttribute
  {
    public override void OnAuthorization(HttpActionContext actionContext) 
      {

        base.OnAuthorization(actionContext);

        // If not authorized at all, don't bother checking for the 
        // customer - order relation
        if (actionContext.Response == null) 
          {
             //Get customer key  
             int customerKey = GetCustomerKey(actionContext.Request.GetRouteData());

             //Check customer-order relation
            if (!customer.Name.Equals(Thread.CurrentPrincipal.Identity.Name)) 
             {
               actionContext.Response = request.CreateResponse(HttpStatusCode.Unauthorized);
             }
           }
       }
  }

Question:

Looking at the author's code : if (actionContext.Response == null) {...} and his comment : "If not authorized at all"

— Is this the right way for checking if an exception has not occurred in the OnAuthorization method ? Checking for Response == null ? (which means : no exception output from the base.OnAuthorization) ?

(Seems strange to me , because an exception can occur and still response to be null.....or am I wrong ? Also - the last thing I want to do is to start investigate headers codes for errors...)

NB

My question is targeting WebApi1 not 2.x

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

0

Answer is here :

Read Badri's last comment in his answer

Custom Authorization in Asp.net WebApi - what a mess?

also here https://i.stack.imgur.com/dNLyL.jpg

Community
  • 1
  • 1
Royi Namir
  • 144,742
  • 138
  • 468
  • 792