Hide stack traces in a smart way in Azure API Management

Stack traces are a nice gift for hackers, because they reveal details about the underlying technology that you are using.  From a security perspective, it is good to remove stack traces when exceptions occur and just return a generic error message, like I described in this blog post.  However, such a generic exception message doesn’t really help with troubleshooting issues when third parties try to consume your APIs.  This blog describes a clever way to find the balance between security and usability.

Configure Application Insights

Ensure that your API Management and the backend API (optionally) are configured to send their application logs to Application Insights.  To be able to track each individual request, it is advised to give it a unique Id and log that one explicitly to App Insights, via the trace policy.  This might look like this:

<!--Use consumer correlation id or generate new one-->
<set-variable name="correlation-id" value="@(context.Request.Headers.ContainsKey("x-correlation-id") ? context.Request.Headers.GetValueOrDefault("x-correlation-id") : Guid.NewGuid().ToString())" />

<!--Set header for end-to-end correlation-->
<set-header name="x-correlation-id" exists-action="override">
    <value>@((string)context.Variables["correlation-id"])</value>
</set-header>

<!--Trace the correlation id-->
<trace source="Global APIM Policy" severity="information">
    <metadata name="correlation-id" value="@((string)context.Variables["correlation-id"])" />
</trace>

Include the Id in the response

Update your generic response, so it includes that unique Id.  In this example, I point them to the support team:

<on-error>
    <set-body template="none">@($"Something went wrong.  Please contact support with this correlation id: {(string)context.Variables["correlation-id"]}.")</set-body>
</on-error>

Conclusion

Some little tricks can improve the usability of your APIs a lot, while still applying to high security standards!

Cheers,
Toon

ABOUT

MEET THE YOUR AZURE COACH TEAM

Your Azure Coach is specialized in organizing Azure trainings that are infused with real-life experience. All our coaches are active consultants, who are very passionate and who love to share their Azure expertise with you.