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.
Step 2
Create an API App as shown below.
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using Swashbuckle.Swagger.Annotations;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using Microsoft.Azure.ServiceBus;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using WebApplication5.Models;
- namespace WebApplication5.Controllers {
- public class ValuesController: ApiController {
- const string ServiceBusConnectionString = "Endpoint=sb://yiintergration.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=ep+4iaM1XDgl0zVcnDSENHSi05CWtrTSsxvuKpfFy0c=";
- const string QueueName = "eyiintegration";
- static IQueueClient queueClient;
-
- [SwaggerOperation("Create")]
- [SwaggerResponse(HttpStatusCode.Created)]
- public string Post(WorkProducts w) {
- const int numberOfMessagesToSend = 1;
- queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
- try {
- int Count = w.result.Count;
- for (var i = 0; i < Count; i++) {
- string workProduct = JsonConvert.SerializeObject(w.result[i]);
-
-
- var message = new Message(Encoding.UTF8.GetBytes(workProduct));
-
-
-
- queueClient.SendAsync(message);
- }
- } catch (Exception exception) {
- Console.WriteLine($ "{DateTime.Now} :: Exception: {exception.Message}");
- }
- return "Successfully received WorkProduct and sent to message queue for further processing ";
- }
Step 4
The registration of the new app in Azure AD is shown below.
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.
Step 6
Please make sure to set the application as Multi-tenanted, as shown below.
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.
Step 8
Set OAuth2AllowImplicitFlow to true by editing the manifest file.
- {
- "appId": "191a48ca-9f41-47c1-a9f4-15c979971df8",
- "appRoles": [],
- "availableToOtherTenants": true,
- "displayName": "testapimab",
- "errorUrl": null,
- "groupMembershipClaims": null,
- "optionalClaims": null,
- "acceptMappedClaims": null,
- "homepage": "https://testapimab.portal.azure-api.net",
- "informationalUrls": {
- "privacy": null,
- "termsOfService": null
- },
- "identifierUris": ["https://aswinbhaskaranabtechnet.onmicrosoft.com/998c1447-8067-48b1-a4b3-c7dee1fd81b4"],
- "keyCredentials": [],
- "knownClientApplications": [],
- "logoutUrl": null,
- "oauth2AllowImplicitFlow": true,
- "oauth2AllowUrlPathMatching": false,
- "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.
Step 10
Click "Add".
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
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).
Step 13
Having configured Reply URLs, now we need to configure the backend APIs to use OpenId Connect.
Step 14
The API which was created in Step 2 needs to be configured now.
Step 15
Select the API App after clicking on the "Browse" button as shown below and select the API App created in Step 2.
Step 16
Select the API App and click "Settings". Now, please make sure you have the correct API URL.
Step 17
Please make sure to select OpenId Connect for User Authorization and select the OpenId Connect Server which was created in Step 11.
Step 18
Now, click on Design and drag and drop the Validate JWT policy within the Inbound Processing, as shown below.
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
- <policies>
- < inbound>
- < validate-jwt header-name=”Authorization” failed-validation-httpcode=”401″ failed-validation-error-message=”Unauthorized. Access token is missing or invalid.”>
- < openid-config url=”https:
- < required-claims>
- < claim name=”aud”>
- < value>191a48ca-9f41-47c1-a9f4-15c979971df8</value>
- < /claim>
- < /required-claims>
- < /validate-jwt>
- < base />
- < /inbound>
- < backend>
- < base />
- < /backend>
- < outbound>
- < base />
- < /outbound>
- < on-error>
- < base />
- < /on-error>
- < /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.
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.
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.
- <add key="UnobtrusiveJavaScriptEnabled" value="true" />
- <add key="ida:ClientId" value="191a48ca-9f41-47c1-a9f4-15c979971df8" />
- <add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
- <add key="ida:AADInstanceLogin" value="https://login.windows.net/{0}" />
- <add key="ida:ClientSecret" value="d3gqg85ro4MV84P+XS5DYhupwRfloJFHoLENmlbQBuA=" />
- <add key="ida:AppKey" value="d3gqg85ro4MV84P+XS5DYhupwRfloJFHoLENmlbQBuA=" />
- <add key="ida:Domain" value="aswinbhaskaranabtechnet.onmicrosoft.com" />
- <add key="ida:Tenant" value="aswinbhaskaranabtechnet.onmicrosoft.com" />
- <add key="ida:TenantId" value="c683b381-c32e-4bc5-926c-a0a9371a336f" />
- <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.
Step 24 - JWT(Access Token)
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.
Step 26
The entire Auth Code flow,
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.