Adding Entra Authentication and Authorization to a .NET Blog API
Because I already have a working implementation in Trakr, I provided Codex with a reference for the authentication pattern I’m looking for rather than asking it to design the integration from scratch. I used this prompt:
let's implement entra into this api
1280c0a9-3d61-4912-a7a3-031cb4699950 is my tenant
76162626-f290-4517-ace4-14e3af2d46e8 is the client id for this api
you can reference how I implemented it in Trakr if necessary.
Requirements
- All requests must be authorized to access this API
- Users should be able to authorize Swagger using Entra
For this API, I’m exposing a simple Blog.Admin scope. Since this is a small application with a very limited authorization model, a single scope is enough for now. We’re primarily trying to get to the point where we can create our endpoints and begin testing them.
For a deeper look at scopes, roles, and how I might structure identity for a more complex application, see Main Street Identity.
We also need to define a Single-page application (SPA) redirect URI under the app registration’s Authentication settings in Entra:
https://localhost:7036/swagger/oauth2-redirect.html
Next, we add the Entra configuration to appsettings.json:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "1280c0a9-3d61-4912-a7a3-031cb4699950",
"ClientId": "76162626-f290-4517-ace4-14e3af2d46e8",
"ApplicationIdUri": "api://76162626-f290-4517-ace4-14e3af2d46e8",
"Scope": "Blog.Admin"
}
}
The Tenant ID, Client ID, Application ID URI, and scope names shown here are identifiers, not credentials. They are expected to be visible to clients. Client secrets, private keys, access tokens, and similar credentials should never be committed or published.
The next step is to configure Swagger so we can authenticate against Entra while testing the API.
Starting with .NET 9, ASP.NET Core includes built-in OpenAPI document generation, and Swashbuckle is no longer included by default in new project templates. Swashbuckle is still available as a community package and can be added manually.
I continue to use Swagger UI largely out of familiarity. It provides a simple, intuitive interface for exploring and testing an API without introducing much additional maintenance overhead.
For larger APIs, platforms such as Azure API Management can provide significantly more functionality around API discovery, governance, security, policies, analytics, and developer onboarding. For this project, however, Swagger is more than sufficient for local development and testing.
To keep Program.cs clean, I use dependency injection extension methods to organize service registrations into facades, typically per feature. I’ll expand on this pattern later as the application gains more features.
First, EntraSettings reads the required values from configuration and fails early when one is missing:
namespace bpe_blog_api.Extensions;
internal sealed record EntraSettings(
string Instance,
string TenantId,
string ClientId,
string ApplicationIdUri,
string Scope)
{
public static EntraSettings FromConfiguration(IConfiguration configuration)
{
var azureAd = configuration.GetRequiredSection("AzureAd");
return new EntraSettings(
GetRequiredValue(azureAd, "Instance").TrimEnd('/'),
GetRequiredValue(azureAd, "TenantId"),
GetRequiredValue(azureAd, "ClientId"),
GetRequiredValue(azureAd, "ApplicationIdUri").TrimEnd('/'),
GetRequiredValue(azureAd, "Scope"));
}
private static string GetRequiredValue(IConfigurationSection section, string key) =>
section[key]
?? throw new InvalidOperationException($"{section.Path}:{key} is required.");
}
The authentication extension configures JWT bearer authentication with the Entra tenant as the authority and validates tokens against the API’s supported audiences:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
namespace bpe_blog_api.Extensions;
public static class EntraAuthenticationExtensions
{
public static IServiceCollection AddEntraAuthentication(
this IServiceCollection services,
IConfiguration configuration)
{
var settings = EntraSettings.FromConfiguration(configuration);
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = $"{settings.Instance}/{settings.TenantId}/v2.0";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
ValidAudiences = [settings.ApplicationIdUri, settings.ClientId]
};
});
return services;
}
}
The Swagger extension defines the OAuth 2.0 authorization-code flow and configures Swagger UI to use PKCE:
using Microsoft.OpenApi;
namespace bpe_blog_api.Extensions;
public static class SwaggerExtensions
{
private const string SecuritySchemeName = "oauth2";
public static IServiceCollection AddSwaggerWithEntra(
this IServiceCollection services,
IConfiguration configuration)
{
var settings = EntraSettings.FromConfiguration(configuration);
var scope = $"{settings.ApplicationIdUri}/{settings.Scope}";
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "BPE Blog API",
Version = "v1"
});
options.AddSecurityDefinition(SecuritySchemeName, new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri(
$"{settings.Instance}/{settings.TenantId}/oauth2/v2.0/authorize"),
TokenUrl = new Uri(
$"{settings.Instance}/{settings.TenantId}/oauth2/v2.0/token"),
Scopes = new Dictionary<string, string>
{
[scope] = "Access the BPE Blog API on your behalf"
}
}
}
});
options.AddSecurityRequirement(document => new OpenApiSecurityRequirement
{
[new OpenApiSecuritySchemeReference(
SecuritySchemeName,
document,
externalResource: null)] = [scope]
});
});
return services;
}
public static IApplicationBuilder UseSwaggerUiWithEntra(
this IApplicationBuilder app,
IConfiguration configuration)
{
var settings = EntraSettings.FromConfiguration(configuration);
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "BPE Blog API v1");
options.OAuthAppName("BPE Blog API");
options.OAuthClientId(settings.ClientId);
options.OAuthUsePkce();
options.OAuthScopes($"{settings.ApplicationIdUri}/{settings.Scope}");
});
return app;
}
}
With those extensions in place, the Entra-related portions of Program.cs stay focused:
builder.Services.AddEntraAuthentication(builder.Configuration);
builder.Services
.AddAuthorizationBuilder()
.SetFallbackPolicy(new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build());
builder.Services.AddSwaggerWithEntra(builder.Configuration);
// Build the application and configure the development pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUiWithEntra(builder.Configuration);
}
app.UseAuthentication();
app.UseAuthorization();
And with that, we’ve added basic authentication and authorization to the Blog API using Entra, Swagger, and .NET.