The sample web API application in this blog uses .Net 6 Framework and Microsoft.Identity.Web nuget package to Azure AD protect the Web API. I use Serilog framework for logging the debug output both to the console window and to the local file. This sample assumes you already have a web API application registered in Azure AD. If you are not familiar with how to do that refer to my previous blog on the same web API protection topic. To troubleshoot web API Authentication/Authorization issues, we can take advantage of the following JWTBearerEvents to get insight into why a JWT Bearer token might fail to validate: OnTokenValidated, OnMessageReceived, OnAuthenticationFailed, and OnChalleenge events.

Here is how I configure the App ID URI for my Web API

You can find the source code for this project on github. Below is my Program.cs file showing how to set up logging for the above events:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using Microsoft.IdentityModel.Logging;
using System.Diagnostics;
using Serilog;


Log.Logger = new LoggerConfiguration()

Log.Information("starting up");
    var builder = WebApplication.CreateBuilder(args);

    builder.Host.UseSerilog((ctx, lc) => lc

    // Add services to the container.

    // Enable PII for logging
    IdentityModelEventSource.ShowPII = true;
    // Configure middleware events
    builder.Services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
        options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            ValidAudiences = new List<string> { "api://a56797c4-e6f7-4d8c-89cc-0b3cc64d8b3e", "a56797c4-e6f7-4d8c-89cc-0b3cc64d8b3e" },
            ValidIssuers = new List<string> { "<tenant ID>/", "<tenant ID>/v2.0" }
        options.Events = new JwtBearerEvents
            OnTokenValidated = ctx =>
                string message = "[OnTokenValidated]: ";
                message += $"token: {ctx.SecurityToken.ToString()}";
                return Task.CompletedTask;
            OnMessageReceived = ctx =>
                string message = "[OnMessageReceived]: ";
                ctx.Request.Headers.TryGetValue("Authorization", out var BearerToken);
                if (BearerToken.Count == 0)
                    BearerToken = "no Bearer token sent\n";
                message += "Authorization Header sent: " + BearerToken + "\n";
                return Task.CompletedTask;
            OnAuthenticationFailed = ctx =>
                ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
                string message = $"[OnAuthenticationFailed]: {ctx.Exception.ToString()}";
                // Debug.WriteLine("[OnAuthenticationFailed]: Authentication failed with the following error: ");
                // Debug.WriteLine(ctx.Exception);
                return Task.CompletedTask;
            OnChallenge = ctx =>
                // Debug.WriteLine("[OnChallenge]: I can do stuff here! ");
                return Task.CompletedTask;
            OnForbidden = ctx =>
                return Task.CompletedTask;

    // Learn more about configuring Swagger/OpenAPI at
    // builder.Services.AddEndpointsApiExplorer();
    // builder.Services.AddSwaggerGen();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
        // app.UseSwagger();
        // app.UseSwaggerUI();
        // do something




catch (Exception ex)
    Log.Fatal(ex, "Unhandled exception");
    Log.Information("Shut down complete");

To run this sample change the following section with your own app registration info:

  • the AzureAD section in appsettings.json file
  • TokenValidationParameters’s ValidAudiences and ValidIssuers in Program.cs

The sample writes log output to both a console window and local file whose path is specified in appsettings.json

Leave a Comment