Configure OpenId Connect In Azure API Management

The following topics will be covered in this post.

  • Create APIM
  • Create API
  • App registration in Azure AD
  • Configure APIM to use OpenId Connect (Create Authorization Server)
  • Configure Reply URLs for Developer Portal and Prod App
  • Configure API to use OpenId connect
  • Test using Developer Portal
  • Test using MVC Client Application

It is assumed that you are having an Azure subscription with access to Azure AD in the tenant.

Step 1 - Create APIM 

Complete the mandatory fields as applicable and click the "Create" button to create APIM.

Configure OpenId Connect In Azure API Management

Step 2

Create an API App as shown below.
 
Configure OpenId Connect In Azure API Management 

Step 3

Create an API App project in Visual Studio 2017 and deploy the code into the API App created in the previous step. Here, we are seeing a POST operation which accepts JSON as an input and returns a string.
 
Code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using Swashbuckle.Swagger.Annotations;  
  8. using System.Text;  
  9. using System.Threading;  
  10. using System.Threading.Tasks;  
  11. using Microsoft.Azure.ServiceBus;  
  12. using Newtonsoft.Json;  
  13. using Newtonsoft.Json.Linq;  
  14. using WebApplication5.Models;  
  15. namespace WebApplication5.Controllers {  
  16.         public class ValuesController: ApiController {  
  17.                 const string ServiceBusConnectionString = "Endpoint=sb://yiintergration.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=ep+4iaM1XDgl0zVcnDSENHSi05CWtrTSsxvuKpfFy0c=";  
  18.                 const string QueueName = "eyiintegration";  
  19.                 static IQueueClient queueClient;  
  20.                 // POST api/values  
  21.                 [SwaggerOperation("Create")]  
  22.                 [SwaggerResponse(HttpStatusCode.Created)]  
  23.                 public string Post(WorkProducts w) {  
  24.                     const int numberOfMessagesToSend = 1;  
  25.                     queueClient = new QueueClient(ServiceBusConnectionString, QueueName);  
  26.                     try {  
  27.                         int Count = w.result.Count;  
  28.                         for (var i = 0; i < Count; i++) {  
  29.                             string workProduct = JsonConvert.SerializeObject(w.result[i]);  
  30.                             // Create a new message to send to the queue.  
  31.                             //string messageBody = workProduct..ToString();  
  32.                             var message = new Message(Encoding.UTF8.GetBytes(workProduct));  
  33.                             // Write the body of the message to the console.  
  34.                             //Console.WriteLine($"Sending message: {messageBody}");  
  35.                             // Send the message to the queue.  
  36.                             queueClient.SendAsync(message);  
  37.                         }  
  38.                     } catch (Exception exception) {  
  39.                         Console.WriteLine($ "{DateTime.Now} :: Exception: {exception.Message}");  
  40.                     }  
  41.                     return "Successfully received WorkProduct and sent to message queue for further processing ";  
  42.                 }  
Step 4
 
The registration of the new app in Azure AD is shown below.

Configure OpenId Connect In Azure API Management

Step 5

Select "All Apps" in the "App registrations" window in Azure AD and you should see the latest app which was registered, as shown below.

Configure OpenId Connect In Azure API Management

Step 6

Please make sure to set the application as Multi-tenanted, as shown below.

Configure OpenId Connect In Azure API Management

Step 7

Generate an App Key and make sure to note it down in a notepad. We will need this while configuring the OpenId Connect within APIM.

Configure OpenId Connect In Azure API Management

Step 8

Set OAuth2AllowImplicitFlow to true by editing the manifest file.
  1. {  
  2.     "appId""191a48ca-9f41-47c1-a9f4-15c979971df8",  
  3.     "appRoles": [],  
  4.     "availableToOtherTenants"true,  
  5.     "displayName""testapimab",  
  6.     "errorUrl"null,  
  7.     "groupMembershipClaims"null,  
  8.     "optionalClaims"null,  
  9.     "acceptMappedClaims"null,  
  10.     "homepage""https://testapimab.portal.azure-api.net",  
  11.     "informationalUrls": {  
  12.         "privacy"null,  
  13.         "termsOfService"null  
  14.     },  
  15.     "identifierUris": ["https://aswinbhaskaranabtechnet.onmicrosoft.com/998c1447-8067-48b1-a4b3-c7dee1fd81b4"],  
  16.     "keyCredentials": [],  
  17.     "knownClientApplications": [],  
  18.     "logoutUrl"null,  
  19.     "oauth2AllowImplicitFlow"true,  
  20.     "oauth2AllowUrlPathMatching"false,  
  21.     "oauth2Permissions": [  
Step 9
 
Having completed the App registrations, we need to configure the OpenId Connect Provider in APIM as shown below. Navigate to APIM which we have created in Step 1 and click on OpenId Connect in Security within APIM.

Configure OpenId Connect In Azure API Management

Step 10

Click "Add".

Configure OpenId Connect In Azure API Management

Step 11

Please make sure to note the implicit glow and authorization code flow redirect URI from this step and click "Create".

The  Metadata Endpoint URL will be your Azure AD Metadata Endpoint URL. Please make sure to replace the underscores with your Azure TenantId.

https://login.microsoftonline.com/c683b381-c32e-4bc5-926c-a0a9371a336f/.well-known/openid-configuration

Configure OpenId Connect In Azure API Management

Step 12 - Configure Redirect URI

This is a very critical step. Please make sure to create both the Implicit Flow and Authorization Code Flow redirect URL within AD App as shown below. The redirect URI from Step 11 needs to be pasted here. After successful authentication, the Authorization Code (Authorization Flow) and Access Token (Implicit Flow) will be returned to this URL within the response header while using the developer portal. And if you are using custom MVC Application, then you will have a similar URL as shown in the first line below. The Production application URL will be configured as shown below (last line).

Configure OpenId Connect In Azure API Management

Step 13

Having configured Reply URLs, now we need to configure the backend APIs to use OpenId Connect.

Configure OpenId Connect In Azure API Management

Step 14

The API which was created in Step 2 needs to be configured now.

Configure OpenId Connect In Azure API Management

Step 15

Select the API App after clicking on the "Browse" button as shown below and select the API App created in Step 2.

Configure OpenId Connect In Azure API Management

Step 16

Select the API App and click "Settings". Now, please make sure you have the correct API URL.

Configure OpenId Connect In Azure API Management

Step 17

Please make sure to select OpenId Connect for User Authorization and select the OpenId Connect Server which was created in Step 11.

Configure OpenId Connect In Azure API Management

Step 18

Now, click on Design and drag and drop the Validate JWT policy within the Inbound Processing, as shown below.

Configure OpenId Connect In Azure API Management
Step 19
 
Now, update the Validate JWT Token as shown below.
  • Open-Config-url should be Azure AD Metadata URL and the highlighted should be replaced with the Tenant Id. Refer to Step 11.
  • Aud claim value should be APIM Client Id from App registration. Refer to Step 5

  1. <policies>  
  2.    < inbound>  
  3.       < validate-jwt header-name=”Authorization” failed-validation-httpcode=”401″ failed-validation-error-message=”Unauthorized. Access token is missing or invalid.”>  
  4.          < openid-config url=”https://login.microsoftonline.com/c683b381-c32e-4bc5-926c-a0a9371a336f/.well-known/openid-configuration” />  
  5.             < required-claims>  
  6.                < claim name=”aud”>  
  7.                   < value>191a48ca-9f41-47c1-a9f4-15c979971df8</value>  
  8.                < /claim>  
  9.             < /required-claims>  
  10.       < /validate-jwt>  
  11.    < base />  
  12. < /inbound>  
  13. < backend>  
  14.    < base />  
  15. < /backend>  
  16. < outbound>  
  17. < base />  
  18.       < /outbound>  
  19.             < on-error>  
  20.       < base />  
  21.    < /on-error>  
  22. < /policies>  

Step 20

With this, all the steps required for configuring OpenId Connect for APIM and securing the back-end API have been completed. Click on the Developer Portal as shown below and test the APIM.

Configure OpenId Connect In Azure API Management

Step 21

In Developer Portal, click APIs in the top navigation and click the appropriate API which has been created and click on "Try it". Please make sure to copy the JSON in Request body if your API is going to accept JSON as Input and in Authorization, you can find the Authorization server (testapimab in this case). Select Authorization code. Now, you will be presented with the dialog to sign in. Please make sure to select an appropriate account. Click "Send" and you should see a response from the APIM.

Configure OpenId Connect In Azure API Management

Step 22

Download the sample client code from git hub. And update the web.config with appropriate ClientId(App key from App Registration), ClientSecret(Key from App registration), Domain and Tenant should be AD name, TenantId should be AD Tenant Id.

  1. <add key="UnobtrusiveJavaScriptEnabled" value="true" />  
  2. <add key="ida:ClientId" value="191a48ca-9f41-47c1-a9f4-15c979971df8" />  
  3. <add key="ida:AADInstance" value="https://login.microsoftonline.com/" />  
  4. <add key="ida:AADInstanceLogin" value="https://login.windows.net/{0}" />  
  5. <add key="ida:ClientSecret" value="d3gqg85ro4MV84P+XS5DYhupwRfloJFHoLENmlbQBuA=" />  
  6. <add key="ida:AppKey" value="d3gqg85ro4MV84P+XS5DYhupwRfloJFHoLENmlbQBuA=" />  
  7. <add key="ida:Domain" value="aswinbhaskaranabtechnet.onmicrosoft.com" />  
  8. <add key="ida:Tenant" value="aswinbhaskaranabtechnet.onmicrosoft.com" />  
  9. <add key="ida:TenantId" value="c683b381-c32e-4bc5-926c-a0a9371a336f" />  
  10. <add key="ida:PostLogoutRedirectUri" value="https://localhost:44346/" />  
Step 23
 
You may have to update the code within GetAPIMDemoValues() method within APIMDemoControl.cs to consume the APIM and send the appropriate JSON.

The initial request to get the Authorization Code from OpenId Provider will be called from Configure App method in Startup.Auth.cs. And the Authorization Code wilAuthorization Code will be cached using ADAL.cs. And the Access Token will be acquired when GetTokenForBackendApplication() method is called. Please make sure to update the Subscription key within GetAPIMDemoValues() method.

Configure OpenId Connect In Azure API Management

Step 24 - JWT(Access Token)

Configure OpenId Connect In Azure API Management

Step 25
 
Configure Authentication to secure the backend API using Azure AD Authentication. If this step is not done anyone can access your backend api. By completing this step only those requests which pass through APIM can access the API using the access token from APIM.

Configure OpenId Connect In Azure API Management

 

Step 26

The entire Auth Code flow,

Configure OpenId Connect In Azure API Management

Conclusion

In this post we have seen how to configure APIM with OpenId Connect Authentication/Authorization(uses OAuth2.0) and test using Developer Portal and MVC Client Application. And we also seen how we can configure Azure AD Authenticaiton to secure backend API.
 
Also find the modified source attached for your reference.