Using OAuth 2.0 to protect APIs published on Azure APIM (API Management Gateway)

As OAuth 2.0 offers different flows, or grant types, to cover multiple authorisation scenarios, it can also be used to protect APIs published on Azure API Management Gateway (APIM). The flow that can be used to allow OAuth 2.0 authorisation between applications is the client credentials flow.

When exposing APIs on Azure APIM, we usually have service to service communication, without any form of user interaction, where APIs are consumed by other applications. The writing below covers how to use the client credentials flow to protect the APIs, how to cofigure Azure APIM with OAuth 2.0 to also allow to the the published APIs from Developer Portal, using OAuth 2.0 authorisation and also C# sample code to connect to an API and authorize using OAuth 2.0.

Prerequsites

Protocol diagram

According to official Microsoft documentation, the following diagram represents the client credentials flow:

OAuth 2.0 client credentials flow

An app typically receives direct authorization to access a resource in one of two ways:

These two methods are the most common in Azure AD and are recommended for clients and resources that perform the client credentials flow. A resource can also choose to authorize its clients in other ways. Each resource server can choose the method that makes the most sense for its application.

Instead of using ACLs, you can use APIs to expose a set of application permissions. An application permission is granted to an application by an organization’s administrator, and can be used only to access data owned by that organization and its employees.

The current setup will contain an Azure APIM instance, a test API published (the out of the box Echo API), a policy for the API and two applications that will be created in Azure AD tenant.

First step is to deploy an Azure APIM instance, using Azure Portal. After deployment is complete, we already have a standard test API, Echo API, published as a test.

For making thing easier on the testing side, I created a simple policy in the inbound processing step to return 200 OK message if the client call reached the API.

<inbound>
        <return-response>
            <set-status code="200" />
            <set-header name="content-type" exists-action="override">
                <value>application/json</value>
            </set-header>
            <set-body>
            {
            "status": "200",
            "message": "OK"
            }
            </set-body>
        </return-response>
        <base />
</inbound>

Using VS Code and Rest Client Extension, writing the following request:

We will get the following result:

Which is perfectly fine, API is alive and responsive.

Now I had to create two application registrations in Azure AD, which enables the creation of the OAuth 2.0 authorisation with client credentials flow. Follow the instructions from Microsoft documentation here, as in the following steps I will need this setup to also enable authorisation for API from Developer Portal of Azure APIM.

I’ve created two apps registration, one representing the API Proxy (backend) and the other one the API Client.

  • ago-apiproxy-oauth-app
  • ago-apiclient-oauth-app

For both applications take note of application ID, as it will be needed later.

Now, for the API client application, a secret needs to be created.

  1. Navigate to the API client app, in my case ago-apiclient-oauth-app.
  2. Navigate to certificates and secrets and add a secret (I kept the default expiration date, as this is just a test setup)
  3. Take note of the generated secret

Now, test the setup in VS Code. In VS Code, these are the settings for the API calls.

Now we are ready to get a JWT token from the token endpoint. The request looks like below (VS Code):

The result of running the above request is a JWT token, like below:

{
  "token_type": "Bearer",
  "expires_in": 3599,
  "ext_expires_in": 3599,
  "access_token": "eyJ0eXAiOiJ........."
}

Next step, as we have the apps registered and can generate a JWT, is to configure Azure APIM to validate the JWT and its claims to see if the client is authorized to call the API.

Some differences from Microsoft documentation:

  • Granting permissions – Above mentioned documentation explains how to grant delegated permissions, which are applicable when we have a signed in user, which is not the case here, when we are dealing with app to app flow. We need to use the application permissions, applicable in app to app scenarios.
  • Enable user authentication in APIM developer portal. If we do that then a some functionalities of the flow will no longer be working for app to app scenario. In the APIM developer portal we are dealing with a signed in user. I will explain later.

Microsoft documentation suggests using a policy in the API inbound processing leg to validate the audience claim (aud)

The above definition means the audience claim should only be used be used to validate that a token was issued targeting our application. This does not imply there are any permissions granted for the caller app.

Now we can test this by adding a validate-jwt policy to the API operation we are testing.

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
            <openid-config url="https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration" />
            <required-claims>
                <claim name="aud" match="any">
                    <value>api://4a41d081-77b5-4936-b87c-52b76b36dbc2</value>
                </claim>
            </required-claims>
        </validate-jwt>

Update: Seems that by some unknown reasons, using tag

<claim name=”aud” match=”any”>
<value>api://4a41d081-77b5-4936-b87c-52b76b36dbc2</value>

is not working anymore. I had to remove the “api://” from the claim value to make it work again. Now it looks like:

<claim name=”aud” match=”any”>
<value>4a41d081-77b5-4936-b87c-52b76b36dbc2</value>

For the test to work, when we call the OAuth 2.0 protected endpoint, we have to add the Authorization header along with the bearer token generated when we called the token endpoint. The request would look like this:

We should be getting a 200 OK response. As we have not given any permission, yet, to the client app to call the proxy (backend) app, validating only the audience claim is not enough. An approach is to also validate the azp claim to check whether the caller is authorized to call the endpoint.

Note: In https://platform.deloitte.com.au/articles/oauth2-client-credentials-flow-on-azure-api-management is it advised to validate the appid claim. However, this claim seems not to be presented in token, at least not for version 2, hence I’ve tested it for azp claim.

Policy for testing botd aud and azp claims:

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
            <openid-config url="https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration" />
            <required-claims>
                <claim name="aud" match="any">
                    <value>api://4a41d081-77b5-4936-b87c-52b76b36dbc2</value>
                    <value>4a41d081-77b5-4936-b87c-52b76b36dbc2</value>
                </claim>
                <claim name="azp" match="any">
                    <value>f73ba7f2-5bf9-44b5-b82c-e4b191a80c41</value>
                </claim>
            </required-claims>
        </validate-jwt>

After testing this, we should get a 200 OK response.

A more advanced scenario is when we would add Application Permission for the client app, to fine grain control of what APIs and API operation the app can call. But if we want this setup to also work in Developer Portal of Azure APIM (users being able to try and test the API from the developer portal)P, then the roles claim is no longer working anymore. In an app to app scenario the token contains the roles claim, but in APIM Developer Portal we have an user already signed in (or asked to sign in) and token is generated based on this user so no more roles claim available.

How to configure APIM Developer Portal is described in details in Microsoft documentation, here. As we already created the apps, continue from “Grant permissions in Azure AD” step. Once configured, for settings to take effect in the new portal, it must be published again. The result is showing the Authorisation field in the Developer Portal when you go an try an API.

Now we have the API published on Azure APIM procted by OAuth 2.0 tokens and also, from the developer portal, we can test it with authorization. As the policies are implemented at API level, without configuring APIM with OAuth 2.0, it would not be possible anymore to use the Azure Portal, always getting an authorisation error.

Visual Studio C# code for accessing the API with token authorization

Code is pretty straight forward. To help with REST calls and JSON objects, I’ve used RestSharp and Newtonsoft.JSON packages.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;

namespace PCBQPCAPITokenAuth
{
    class Program
    {
        static void Main(string[] args)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            Token tok=GetTokenRestSharp();
            Console.WriteLine(tok.AccessToken);

            RestClient client = new RestClient("https://agotestauth.azure-api.net/echo-clone/resource?param1=sample");
          
            RestRequest request = new RestRequest(Method.GET);
            request.AddHeader("Ocp-Apim-Subscription-Key", "your subscrition key");
            request.AddHeader("Authorization", "Bearer " + tok.AccessToken);
            request.AddHeader("cache-control", "no-cache");
            IRestResponse  response = client.Execute(request);

            Console.WriteLine(response.Content.ToString());

            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadKey();
        }

        private static Token GetTokenRestSharp()
        {
            var client = new RestClient("https://login.microsoftonline.com/your azure tennat id/oauth2/v2.0/token");
            var request = new RestRequest(Method.POST);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            string gtype = "client_credentials";
            string cid = "f73ba7f2-5bf9-44b5-b82c-e4b191a80c41";
            string csecret = "your api app secret";
            string scope = "api://4a41d081-77b5-4936-b87c-52b76b36dbc2/.default";
            request.AddParameter("application/x-www-form-urlencoded", "grant_type=" + gtype +"&client_id=" + cid + "&client_secret=" + csecret + "&scope=" + scope, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            Token tok = JsonConvert.DeserializeObject<Token>(response.Content.ToString());
            return tok;
        }

        internal class Token
        {
            [JsonProperty("token_type")]
            public string TokenType { get; set; }

            [JsonProperty("expires_in")]
            public string ExpiresIn { get; set; }

            [JsonProperty("ext_expires_in")]
            public int ExtExpiresIn { get; set; }

            [JsonProperty("access_token")]
            public string AccessToken { get; set; }
        }

    }
}

Resources used: