Connect An Azure AD-Secured API Using Application ID

Introduction

 
This blog describes the steps to connect an Azure AD-secured API with a client ID. These steps will be helpful to call the secured API with the application access. 
 
Prerequisites

To follow the steps in this article you should have:
  • An Azure AD tenant.
  • An API hosting azure service.
  • Access to register the app in Azure AD.

Overview

  1. Create a serverless API and authenticate it using Azure AD.
  2. Register an application in Azure AD to represent the API and create the secret key to access the API.
  3. If required, provide permission to the Azure app, to access specific scope.
  4. Create a bearer token using App ID and access the resource.
Register an application in Azure AD to represent the API:
  • Go to the Azure portal. Create the APP from New registration under Active Directory. For more details, please visit here.
  • Create the secret key to access the API.

Create a Secured API


Create a sample API and host the same into the Azure function. Authenticate the same using the Azure active directory. Now, the API is secured and only the users who have been part of AD can access the API.
 
To secure the API, Go to the Azure function, select the Authentication and Authorization under the security section.
 
Select the Azure Active directory, and select the app that we created above. For more details, please visit here.
 
Sample API
 
https://blogs.azurewebsites.net. This API is AD protected, hence it cannot be accessed without proper authentication.
 

Create a Bearer Token and Access the Resource


To create the access token, use the below details:
  1. URL: https://login.microsoftonline.com/{{Tenant}}/oauth2/token  
  2. Method: POST  
  3. Headers: Content-Type: application/x-www-form-urlencoded  
  4. Body:  
  5. {  
  6.    grant_type:client_credentials  
  7.    client_id: {{App ID}}  
  8.    client_secret:{{secret key}}  
  9.    resource:{{App ID}}  
  10. }   
Response
 
The following is an example of the response:

  1. HTTP/1.1 200 OK  
  2. {  
  3.    "token_type""Bearer",  
  4.    "expires_in""3599",  
  5.    "ext_expires_in""3599",  
  6.    "expires_on""",  
  7.    "not_before""",  
  8.    "resource""",  
  9.    "access_token"""  
  10. }   
The access token in the response will be used to access the resource.

  1. API Url: https://blogs.azurewebsites.net  
  2. Headers: Authorization: Bearer {{access_token}}   
Bingo! Now you can access the API.
 
Cheers! Happy Coding!