APIM invalid subscription key returns 500 error instead of 401

Nikolaj LARSEN 20 Reputation points
2023-11-22T14:12:17.6766667+00:00

We have an API Management Service configured, using Subscriptions for authentication. We're playing around with creating a policy to perform some action when the authentication fails for a consumer. So we created the following policy:

<on-error>
    <base />
    <choose>
        <when condition="@(context.Response.StatusCode == 401)">
            <return-response>
                <set-status code="200" />
                <set-body>Something went wrong.</set-body>
            </return-response>
        </when>
    </choose>
</on-error>

The issue is that the condition is never met. Apparently, the Status Code being used for invalid or missing subscription key, is the status code "500 Internal Server Error", rather than the expected "401 Unauthorized".

This behavior is rater weird. Can someone explain, why a failed authentication, doesn't produce an "401 Unauthorized" response? It makes it difficult to specifically target authentication errors.

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
1,941 questions
Azure
Azure
A cloud computing platform and infrastructure for building, deploying and managing applications and services through a worldwide network of Microsoft-managed datacenters.
1,063 questions
{count} votes

Accepted answer
  1. JananiRamesh-MSFT 23,486 Reputation points
    2023-12-07T16:40:33.8333333+00:00

    @Nikolaj LARSEN Thanks for reaching out. I had tried this at my end and below are my observations.

    We have this option "Subscription required" for an API in the settings tab.

    If you don't pass the subscription key in the request, and your API is configured to require a subscription key, Azure API Management will return a 401 Unauthorized response with an error message indicating that a subscription key is required before even the policies are executed.

    If the "Subscription required" option is unchecked, Azure API Management will not look for the subscription key in the request for authentication. In this case, the context.Subscription.Id expression will evaluate to null. Thats the reason you get 500 response code. User's image

    Please verify and do let me know if you have any queries.

    Please 'Accept as answer' and ‘Upvote’ if it helped so that it can help others in the community looking for help on similar topics.


0 additional answers

Sort by: Most helpful