Search code examples
azure-api-management

How Do I Throw An Error In Azure API Management Policy?


In my Azure API Management Policy I am checking for some headers and do certain actions depending on what is found.

How do I throw an error when none of the conditions are matched (i.e. in the otherwise block)

<policies>
  <inbound>
    <choose>
      <when condition="">

      </when>
      <when condition="">

      </when>
      <otherwise>

      </otherwise>
    </choose>
    <base/>
  </inbound>

  <backend>
    <base/>
  </backend>
  <outbound>
    <base/>
  </outbound>
  <on-error>
    <base/>
  </on-error>
</policies>

I probably want to return a 401 since I am checking groups in the headers.


Solution

  • You can use a <choose> policy to detect and report failure, return a 401 response.

    <otherwise>
        <return-response >
            <set-status code="401" reason="Unauthorized" />
            <set-header name="WWW-Authenticate" exists-action="override">
                <value>Bearer error="invalid_token"</value>
            </set-header>
        </return-response>
    </otherwise>
    

    Here is also a similar SO thread you could refer to.