How can I make IsAuthorized return my custom object while function returns false?
In my WebAPI project I have a class like;
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse()
{
code = (int) Constants.ErrorCodes.InvalidCredentials,
data = "InvalidCredentials.",
StatusCode = HttpStatusCode.Unauthorized
};
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
invalidUserResponse);
// if I set this to true I am getting 401 with my custom object
// otherwise it gives me default error message
// {"Message":"Authorization has been denied for this request."}
return false;
}
}
For some reason when I return false from IsAuthorized function, it does not return my custom invalidUserResponse object. But if I return true it returns it.
How can I resolve this issue?
I know this question has been answered but I feel like it is slightly wrong. I don't think that a message for unauthorized request should be handled by OnAuthorization but should be handled by HandleUnauthorizedRequest. I'm not sure if it will cause any major problems putting it in OnAuthorization, but presumably the reason you were getting the message when true and not false is because the base class writes over your response in HandleUnauthorizedRequest.
It is a subtle thing but the OnAuthorization directs to the HandleUnauthorizedRequest for a reason. It is mainly a separation of responsibilities thing, but if you ever want to do more than just sending an error message, like log bad request your OnAuthorization method will probably get crowded. You should used the methods given to you for clarity sake if nothing else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With