Securing a Web API using Azure AD and Consuming it with Swagger - Step by Step Guide

 Introduction:

we will walk you through the process of securing a Web API using Azure AD (Azure Active Directory) and generating tokens through Swagger to call this protected API. Securing your APIs is crucial to protect sensitive data and ensure only authorized applications can access them. We'll break down the process into easy-to-follow steps.

Prerequisites:

Before we begin, make sure you have the following prerequisites in place:

An Azure account with the necessary permissions.

Visual Studio or a similar code editor.

Basic knowledge of .NET Core and Swagger.

Github Repository: Secure the Web API using Azure AD

Steps to Secure the Web API using Azure AD:

Step 1: Create Two App Registrations

We need to create two Azure AD App Registrations, one for the Web API and the other for the Swagger client application.

Create a new App Registration named "EmployeeWebApi."

Leave the Redirect URI empty.











Create a new App Registration named "EmployeeClientApp."

Click "Add a platform," select "Single-page applications," provide your Swagger URL (e.g., https://localhost:yourport/swagger/oauth2-redirect.html), and select "access token (used for implicit flows)."






























Step 2: Configure EmployeeWebApi App Registration

In the "EmployeeWebApi" App Registration, go to the "Expose an API" tab.

Set the Application ID URI and click Save.








Click "Add a scope," provide scope information, and click "Add scope."












Click "Add a client application," provide the client app (EmployeeClientApp - Swagger) URL, select the scope, and click "Add application."










Step 3: Configure EmployeeClientApp (Swagger)

In the "EmployeeClientApp" App Registration, go to the "API permissions" tab.

Click "Add a permission" > "My APIs" > "EmployeeWebApi" > select the required permission, and click "Add Permission."













Step 4: .NET Core Application Web API Changes

Make the necessary changes in your .NET Core application's code and configuration:


AppSettings.json

In your "appsettings.json" file, configure the AzureAd and SwaggerClientId settings:

"AzureAd": {

    "Instance": "https://login.microsoftonline.com/",

    "ClientId": "<Your EmployeeWebApi Client ID>",

    "TenantId": "<Your Azure AD Tenant ID>",

    "Scopes": "https://<Your Tenant Name>.onmicrosoft.com/<Your EmployeeWebApi App Name>/<Your Scope>",

    "SwaggerClientId": "<Your EmployeeClientApp (Swagger) Client ID>"

}

Program.cs

In your .NET Core application, update the "Program.cs" file.

using Microsoft.AspNetCore.Authentication.JwtBearer;

using Microsoft.Identity.Web;

using Microsoft.OpenApi.Models;


var builder = WebApplication.CreateBuilder(args);

var configuration = builder.Configuration;


// adding azure add authentication

//JwtBearerDefaults.AuthenticationScheme we are mentioned schema as bearer

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

    // it will get azure ad details from the app setting json

    .AddMicrosoftIdentityWebApi(configuration.GetSection("AzureAd"));  


// Add services to the container.

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

builder.Services.AddEndpointsApiExplorer();


builder.Services.AddSwaggerGen(c =>

{

    c.SwaggerDoc("v1", new OpenApiInfo

    {

        Title = "EmployeeSampleWebApi",

        Description ="This is the sample web api application with azure ad and swagger",

        Version = "v1"

    });


    // here we mentioning how our api is protected,

    // when we enable this section only we can see the auhorize button in the swagger page


    c.AddSecurityDefinition("OAuth2", new OpenApiSecurityScheme

    {

        Description = "Azure ad authentication using oauth 2.0 using authorization code flow (PKCE)",

        Name = "OAuth2 Azure ad authentication",

        // we are using OAuth2 authentication type

        Type = SecuritySchemeType.OAuth2,

        // we have 4 flows (Implicit,Password,ClientCredentials and AuthorizationCode), if you want to know about it

        // right OpenApiOAuthFlows and go to definition see those flows

        Flows = new OpenApiOAuthFlows

        {

            // we are using authorizationcode flow 

            AuthorizationCode = new OpenApiOAuthFlow

            {

                // authoriation url 

                AuthorizationUrl = new Uri($"{configuration["AzureAd:Instance"]}{configuration["AzureAd:TenantId"]}/oauth2/v2.0/authorize"),

                // token url

                TokenUrl = new Uri($"{configuration["AzureAd:Instance"]}{configuration["AzureAd:TenantId"]}/oauth2/v2.0/token"),

                Scopes = new Dictionary<string, string>

                {

                    { $"api://{configuration["AzureAd:ClientId"]}/{configuration["AzureAd:Scopes"]}", "Access API as user"}

                }

            }

        }

    });


    // here we are defining how to security requirement should be (needs to learn swagger course to get more inforamtion)

    c.AddSecurityRequirement(new OpenApiSecurityRequirement

    {

        {

            new OpenApiSecurityScheme

            {

                Reference = new OpenApiReference

                {

                    Type = ReferenceType.SecurityScheme,

                    Id = "OAuth2"

                }

            },

            new[]

            {

                $"api://{configuration["AzureAd:ClientId"]}/{configuration["AzureAd:Scopes"]}"

            }

        }


    });;

});


var app = builder.Build();


// Configure the HTTP request pipeline.

if (app.Environment.IsDevelopment())

{

    app.UseSwagger();

    app.UseSwaggerUI(c =>

    {

        // client app id

        c.OAuthClientId(configuration["AzureAd:SwaggerClientId"]);

        // we are using pcke type 

        c.OAuthUsePkce();

        // multiple scope found means we are separting based on space

        c.OAuthScopeSeparator(" ");

    });

}


app.UseHttpsRedirection();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();


app.Run();


Comments

Popular posts from this blog

Azure Service Bus Azure CLI Commands

Service Bus Queues and Topics