© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
A. Satapathi, A. MishraDeveloping Cloud-Native Solutions with Microsoft Azure and .NET https://doi.org/10.1007/978-1-4842-9004-0_5

5. Secure Microservice with Azure AD

Ashirwad Satapathi1   and Abhishek Mishra2
(1)
Gajapati, Odisha, India
(2)
Navi MUmbai, India
 

You must secure the microservices-based applications you are building. Only authorized users and applications who have access to the microservices should be allowed to access them. Azure Active Directory (Azure AD) is an Identity-as-a-Service (iDaaS) offering that you can use to configure authentication for your microservices. You can easily configure Azure AD for your application and use it for authentication and authorization purposes. In the previous chapter we developed a simple Math microservices application and orchestrated it in the Azure Kubernetes Service. However, we did not secure it and anyone could access the application.

In this chapter, you will learn how to secure the Math microservices application using Azure AD. We will also explore the basics of Azure AD.

In this chapter, we will explore the following topics related to microservices and Azure AD:
  • Introduction to Azure AD

  • Create an application in Azure AD

  • Create scopes for the Azure AD application

  • Configure authentication and authorization for the Math microservices application running in Azure Kubernetes Service

After completing this chapter, you’ll understand the fundamentals of Azure AD and be able to secure containerized .NET-based microservices applications running inside Azure Kubernetes Service.

Introduction to Azure AD

As mentioned, Azure AD is an iDaaS offering on Azure. Azure AD is completely managed by the underlying Azure platform. You need not create any additional infrastructure to manage identity and authentication for your application running on Azure. You can configure authentication and authorization for your application with ease. You need to register your application in Azure AD and then you can create users who can use your application. You can also let the application users authenticate using third-party authentication providers like Google, Facebook, and many more. Application users can authenticate using SAML, OAuth, Open ID Connect, or WS-Federation. Azure AD supports modern authentication features like single sign-on (SSO) and multifactor authentication (MFA).

You can integrate applications running on the on-premises server or Azure or any other supported cloud with Azure AD. You can integrate on-premises Active Directory with Azure AD using Azure AD Connect. Both on-premises users and users created in Azure AD can authenticate to applications registered with Azure AD. Using Azure AD, you can configure business-to-business (B2B) scenarios where the businesses can authenticate and authorize their applications and resources. You can also configure business-to-consumer (B2C) scenarios where the end users can authenticate their applications.

Azure AD can help you as a domain controller and you can join your virtual machines to Azure AD that works as domain controller. You can join the on-premises Active Directory and sync the on-premises users and roles to Azure AD. Azure AD is a multitenant directory management service.

You need to complete the following steps to configure your microservices-based application for Azure AD–based authentication:
  1. 1.

    Register an application with Azure AD.

     
  2. 2.

    Create scopes for the application created in Azure AD to perform authorization.

     
  3. 3.

    Create a secret for your registered application.

     
  4. 4.

    Configure your microservices-based application with an Azure AD application ID, secret, and tenant ID.

     

We will follow these steps and configure authentication for the Math microservices application that we developed in Chapter 4.

Register an Application in Azure AD

Let’s go to the Azure portal and register an application in Azure AD default tenant. Click Azure Active Directory as in Figure 5-1.
Figure 5-1

Click Azure Active Directory

Click App registrations and then click New registration as shown in Figure 5-2. This enables us to register a new application in Azure AD.
Figure 5-2

Click App registrations

Provide a name for the application you need to register and then click Register as shown in Figure 5-3.
Figure 5-3

Click Register

The application will get registered. Click Authentication and then click Add platform as shown in Figure 5-4. We need to add a web platform because we need to use this application to authenticate the MathAPI.
Figure 5-4

Click Add a platform

Select Web as shown in Figure 5-5. We need to authenticate a WebAPI.
Figure 5-5

Select Web

We are going to access the application from Postman, so we need to provide the redirect URI of Postman. Once the authentication is successful, the response will get redirected to the Postman from where you are invoking the application. Provide the Postman URL as the redirect URI as shown in Figure 5-6. The URL will standard for all the calls from Postman. You can use the URL as is without any modifications. Click Configure as shown in Figure 5-6.
Figure 5-6

Click Configure

Create the Application Scope

We can use the scope for the registered application to restrict access to the application. To create the application scope, click Expose an API and then click Add a scope as shown in Figure 5-7.
Figure 5-7

Click Add a scope

Keep the application ID URI generated as is, and shown in Figure 5-8, and click Save and continue.
Figure 5-8

Click Save and continue

Provide a name for the scope and other required values as shown in Figure 5-9. Click Add scope. The scope will get added.
Figure 5-9

Click Add scope

Create the Application Secret

We’ll use the secret for the application to access the application from the client, which is Postman in our case. To create the application secret, click Certificates & secrets and then click New client secret as shown in Figure 5-10. Copy the secret value. We will use the secret value later.
Figure 5-10

Click New client secret

Go to the Overview page and copy the application ID and the tenant ID as shown in Figure 5-11.
Figure 5-11

Copy the application ID and tenant ID

Configure MathAPI for Authentication and Authorization

Now we’ll modify the MathAPI project we created in Chapter 4. MathAPI invokes the AddAPI and SubtractAPI services. The AddAPI and SubtractAPI services are not exposed outside the Kubernetes cluster. We can enable authentication for the MathAPI and need not make any changes for AddAPI and SubtractAPI. Open the appsettings.json file in the MathAPI project and add the tenant ID, client ID, scope, and other necessary values as shown in Listing 5-1.
{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "112a00d5-bc7e-4c48-856c-281cff2328bf",
    "ClientId": "56821c5e-c858-4712-9f48-0758a23e4ce2",
    "Scopes": "ReadWrite",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
Listing 5-1

Appsettings.json

Register the authentication service and add the authentication and authorization middleware in the Program.cs file for the MathAPI project. You can replace the code in the Program.cs file with the code specified in Listing 5-2.
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
//Register authentication service
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
//Enable Authentication and authorization middleware
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Listing 5-2

Program.cs

Add the Authorize attribute for the MathController. You can replace MathController.cs file with code as in Listing 5-3. This enables authentication for the MathAPI.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
namespace MathAPI.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class MathController : Controller
    {
        [HttpGet("Get")]
        public string Get(string ops, int a,int b)
        {
            string result = "";
            string url = "";
            string queryStr = "?a=" + a + "&b=" + b;
            if (ops == "add")
            {
                url = "http:// 10.0.156.137/Add" + queryStr;
            }
            else
            {
                url = "http://10.0.143.214/subtract" + queryStr; ;
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            WebResponse response = request.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                result = reader.ReadToEnd();
            }
            return result;
        }
    }
}
Listing 5-3

MathController.cs

We can use the same Azure Kubernetes Service cluster that we have created earlier and have deployed the APIs in Chapter 4. We need to containerize the MathAPI and push it to Azure Container Registry. You need not redeploy the AddAPI and the SubtractAPI to the Kubernetes cluster. We need to deploy the MathAPI service to the cluster. If you have deleted the Azure container registry and the Azure Kubernetes Service, you can follow the instructions provided in Chapter 4 to re-create them. And then deploy the AddAPI and SubtractAPI to the Kubernetes cluster. Follow the steps illustrated in Chapter 4 to containerize and deploy the MathAPI to the Azure Kubernetes Service cluster.

Once the MathAPI deployment is complete, we can use the Postman tool to test the deployed API. Get the External IP address of the MathAPI using the kubectl command as shown in Listing 5-4.
kubectl get services
Listing 5-4

Get Services in the Cluster

Figure 5-12 depicts the response for the command in Listing 5-4.
Figure 5-12

Services in Kubernetes cluster

We can use the URL shown in Listing 5-5 to browse the math service.
http://[External-IP]/Math/Get?ops=subtract&a=4&b=6
Listing 5-5

MathAPI URL in Kubernetes Cluster

Open Postman and create a new request. Click the Authorization tab and select Type as OAuth 2.0 as shown in Figure 5-13.
Figure 5-13

Postman authorization

Provide Auth URL as shown in Listing 5-6. Replace [Tenant ID] with your Tenant ID for Azure AD.
https://login.microsoftonline.com/[Tenant ID]/oauth2/v2.0/authorize
Listing 5-6

Postman Auth URL

Provide the Access Token URL as shown in Listing 5-7. Replace [Tenant ID] with your Tenant ID for Azure AD.
https://login.microsoftonline.com/[Tenant Id]/oauth2/v2.0/token
Listing 5-7

Postman Access Token URL

As shown in Figure 5-14, provide in the Client ID, Client Secret, and Scope fields the information for your application registered in Azure AD. Click Get New Access Token. You will be prompted for your Azure credentials.
Figure 5-14

Click Get New Access Token

Once the authentication is successful, the access token will get generated. Click Use Token as shown in Figure 5-15.
Figure 5-15

Click Use Token

Fire a GET query for the math service URL. You should get the response shown in Figure 5-16. Without the access token, you will get a 401 – Unauthorized error.
Figure 5-16

Postman request and response for math service

Summary

In this chapter, you learned the basic concepts of Azure AD. We registered an application in Azure AD and made necessary configurations in Azure AD to secure the Math microservice running inside the Azure Kubernetes Service cluster. We then modified the MathAPI service that we created in Chapter 4 and added code and configurations for Azure AD authentication.

In the next chapter we will explore how to run APIs in Azure Container Apps.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset