Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return 403 Forbidden from an Azure Function

I am writing an Azure function in c# that performs some custom authorization. If authorization fails, I'd like to return a 403. I've tried the following:

  1. return new ForbidResult(); this gives error message:

    'No authenticationScheme was specified, and there was no DefaultForbidScheme found'

  2. return new StatusCodeResult(403); this just gives me blank page in both Firefox and Edge.

Thoughts?

like image 625
ubienewbie Avatar asked Oct 15 '25 12:10

ubienewbie


2 Answers

Is it a HTTP triggered function?

return new HttpResponseMessage(HttpStatusCode.Forbidden);
like image 105
Chris B Avatar answered Oct 18 '25 11:10

Chris B


For functions with HttpTrigger when custom auth fails (due to missing credentials or insufficient rights or alike), I return like this:

  • for status code only error responses [CreateResponse] (https://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessageextensions.createresponse(v=vs.118).aspx) request.CreateResponse(HttpStatusCode.Unauthorized)
  • for error responses with hint what went wrong CreateErrorResponse request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You have insufficient rights for this mighty resource")

For reference rfc2616, 401 is better suited for case where big nono happened in scope of auth. According to w3 403 means

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

Where 401 states

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information. HTTP access authentication is explained in "HTTP Authentication: Basic and Digest Access Authentication".

This thing from Chris should work as well ;)

like image 33
gaa Avatar answered Oct 18 '25 10:10

gaa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!