In our earlier article, we explained a custom API for fetching the key vault secrets that were built using Azure API Management Gateway and Azure Functions to provide an endpoint for doing the operation. In this blog, we are going to create another endpoint for generating a new Azure Active Directory BearerToken using a managed identity assigned to Azure Function. This API will be using the same architecture as described in the earlier article.
Ok, so now that we have laid the groundwork, let’s begin by understanding why we need this? The first thing that any developer will have to figure out for performing any operations (CRUD) in a controlled Azure environment is a way to authenticate the application with Azure to get the required token, even though Microsoft has provided many custom solutions for authentication which can be implemented in custom applications to retrieve access tokens.
One of the most commonly used authentication approaches is a service principle-based approach where we would create a service principal in Azure Active Directory and then assign required permissions on APIs against which the access token is to be retrieved. After the service principal is created, we will write the authentication module using the created service principal client ID, client secret, and resource URI of the API on which permissions were granted in Azure Active Directory. There are a few problems with this approach:
This is where this particular API comes into the picture. This custom API will take care of the authentication module and can be reused. With this custom API, we will:
As stated above, we are creating this API on the same lines as our previous API so all pre-requisites are applicable here with additional pre-requisite i.e. User Assigned Managed Identity. We have to create a User Assigned Managed Identity in Azure and need to add the same at Azure Function App created in the previous article. Let’s do it by following the below steps.
Once this is done, created identity should be granted with Contribute/Owner access at subscription/resource group under which resources are to be accessed, updated, created, or deleted in Azure.
Note
For details on Managed Identities, please go through this article.
Now that we are ready with all pre-requisites, let’s jump right to writing API code.
Open the master solution created in an earlier article, in VS code, and create a new Azure Function Project with C# as the language, “GenerateBearerToken” as a function name, HTTP Trigger as the Function Template and Authorization level as Anonymous/Function (this is required for API Management). This will create a class file with the name “GenerateBearerToken.cs”.
Now, lets code the Azure Function to generate Bearer Token against Azure Active Directory using User Assigned Managed Identity. Open GenerateBearerToken.cs file and update the below code in it.
#azure #azure-api #aainst-azure