Securing an Azure APIm using OAuth 2.0 Client Credential Grant
There are a few methods to secure API’s on Azure’s API Management platform, and the one we are going to explore is using OAuth 2.0 Client Credential Grant. This will allow us to require an OAuth token (in the Authorization HTTP Header) on every request that is then pre-validated before the request is forwarded to the backend service.
Fortunately there is a step by step guide Protect an API by using OAuth 2.0 with Azure Active Directory and API Management by Microsoft on how to do this, and rather than repeat its steps I will explain some parts that were not overly obvious to me.
What is OAuth 2.0 Client Credential Grant?
OAuth provides for a few authentication flows, and Client Credential Grant is ideal for system to system calls that are not acting as a particular user. A good guide to the different flows is Alex Bilbie’s A Guide to OAuth 2.0 Grants.
How do I get a OAuth 2.0 Token?
You get a OAuth Token as the client application by requesting a token from the token endpoint (in our case hosted by Azure Active Directory). You pass in the Azure Active Directory Id, client id, client secret, and uniquely to Azure the resource we are trying to access (the app id of the API we are accessing). A request looks like the following (with id’s changed):
First I tried to request a token using Postman however it’s built in UI for getting token’s does not allow for the resource parameter, and the token I received was for audience 00000002-0000-0000-c000-000000000000 which is the Graph API.
To request a token from code I spent sometime looking to use an existing library that support OAuth 2.0, however I found them overly complex as they handle all flows. So I have created the following class instead:
What does an OAuth Token Look Like?
Once you have a token you can view it using jwt.io, simply paste it into the site.
- “aud’ is the audience, and is the application id of the API we are accessing. This comes from the resource parameter on the request.
- “appid” is the application id of the client, and comes from the client_id parameter.
- “roles” are the permissions the client has been granted.
The token also includes a signature, and the part I found interesting during my research was that the server can cache the signing certificate meaning that when validating each request it will not always call back to the token issuer.
What are Azure Active Directory Applications?
- The API
- The Developer Portal client
- My client application
A good guide on how to do this is Defining permission scopes and roles offered by an app in Azure AD.
I have then granted the new permissions to the client applications.
How is the OAuth Token Pre-Authorised?
- Specify the configuration url by adding your Active Directory tenant name
- Specify the Application Id of the API. I used a Named value as it will be different in each environment.
- Specify the required role(s).