Building a Custom ASP.NET Core 6 Application with JWT Authentication, Middleware, Logging with AppInsights, Azure KeyVault, and Azure CI/CD Pipelines

Ali Süleyman TOPUZ
3 min readAug 5, 2023

This article will guide you through building a custom ASP.NET Core 6 application from scratch, focusing on JWT (JSON Web Tokens) authentication, middleware implementation, logging with Application Insights, and using Azure DevOps for Continuous Integration and Continuous Deployment (CI/CD) using YAML pipelines.

Step 1: Create a New ASP.NET Core 6 Web API Project

Install the latest .NET 6 SDK from the official Microsoft website. Once done, create a new project with the following command:

dotnet new webapi -n MyCustomAspNetCore6

Step 2: Add JWT Authentication

First, install the Microsoft.AspNetCore.Authentication.JwtBearer NuGet package:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Next, configure JWT Bearer in Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "{AUTHORITY_URL}";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "{ISSUER_URL}",
ValidateAudience = true,
ValidAudience = "{AUDIENCE}",
ValidateLifetime = true,
};
});

// ...

Replace {AUTHORITY_URL}, {ISSUER_URL}, and {AUDIENCE} with your specific JWT provider details.

Step 3: Add a Middleware

Now let’s create a simple middleware for request logging. Create a new file RequestLoggingMiddleware.cs and add the following code:

public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;

public RequestLoggingMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context)
{
Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}");
await _next(context);
}
}

To use this middleware, update the Program.cs file:

var app = builder.Build();

app.UseMiddleware<RequestLoggingMiddleware>();

// ...

Step 4: Implement Logging with AppInsights

First, install the Microsoft.Extensions.Logging.ApplicationInsights NuGet package:

dotnet add package Microsoft.Extensions.Logging.ApplicationInsights

Then, add Application Insights to the services collection in Program.cs:

builder.Services.AddLogging(logging =>
{
logging.AddApplicationInsights("{INSTRUMENTATION_KEY}");
logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information);
});

Replace {INSTRUMENTATION_KEY} with your Application Insights Instrumentation Key.

Step 5: Azure CI/CD Pipelines Configuration

First, you need to have an Azure DevOps account. Once your account is ready, navigate to Pipelines and create a new pipeline.

5.1: Configure the Build Pipeline

Create a new file in your root project directory called azure-pipelines.yml and add the following:

trigger:
- main

pool:
vmImage: 'windows-latest'

variables:
buildConfiguration: 'Release'

steps:
- script: dotnet build --configuration $(buildConfiguration)
displayName: 'Build'

This basic pipeline will trigger on any push to the main branch and run the .NET Build command.

5.2: Configure the Release Pipeline

The release pipeline can be a separate YAML file or part of the azure-pipelines.yml file:

- stage: 'Deploy'
displayName: 'Deploy stage'
jobs:
- deployment: 'DeployJob'
displayName: 'Deploy job'
environment: 'production'
strategy:
runOnce:
deploy:
steps:
- script: echo Hello, world!
displayName: 'Run a one-line script'

Step 6: KeyVault

Step 6.1: Install Required NuGet Packages

First, install the Azure.Extensions.AspNetCore.Configuration.Secrets and Azure.Identity NuGet packages:

dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
dotnet add package Azure.Identity

Step 6.2: Configure Azure Key Vault

Next, you’ll need to configure Azure Key Vault in your Program.cs file:

var builder = WebApplication.CreateBuilder(args);

var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));

builder.Configuration.AddAzureKeyVault(
new Uri("{KEY_VAULT_URI}"), keyVaultClient, new DefaultKeyVaultSecretManager());

// ...

In the above code, replace {KEY_VAULT_URI} with your Key Vault's URI.

Step 6.3: Using Secrets in the Application

After your application is connected to Azure Key Vault, you can use the secrets stored in the Key Vault just like how you would use values in your configuration file:

var mySecret = builder.Configuration["MySecret"];

Step 6: Run the Application

Run your application with the following command:

dotnet run

Conclusion

We’ve walked through the process of setting up an ASP.NET Core 6 Web API application, implementing JWT authentication, creating custom middleware, adding logging with Application Insights, and configuring Azure DevOps for CI/CD pipelines. This tutorial is a great starting point for customizing and expanding according to your application’s requirements. The capabilities of ASP.NET Core 6 and Azure DevOps provide powerful tools to create efficient, scalable, and robust applications.

--

--

Ali Süleyman TOPUZ

Software Engineering and Development Professional. Writes about software development & tech. 📍🇹🇷