Auth Recipe — C# (.NET) — REFERENCE ONLY
Microsoft Identity Web (ASP.NET Core)
NuGet Packages
<PackageReference Include="Microsoft.Identity.Web" Version="3.*" />Program.cs (additions)
Add these lines — do NOT replace the existing file:
using Microsoft.Identity.Web;
// Add after builder creation
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration);
builder.Services.AddAuthorization();
// Add after app build
app.UseAuthentication();
app.UseAuthorization();
// Protected endpoint
app.MapGet("/api/me", [Authorize] (HttpContext ctx) =>
{
var name = ctx.User.FindFirst("name")?.Value;
return Results.Ok(new { name });
});appsettings.json
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "<tenant-id>",
"ClientId": "<client-id>",
"Audience": "api://<client-id>"
}
}⚠️ The
Audiencemust match the Application ID URI of the app registration (typicallyapi://<client-id>). SetAZURE_CLIENT_IDandAZURE_TENANT_IDas app settings in Azure rather than hardcoding them.
Files to Modify
| File | Action |
|---|---|
Program.cs | Add authentication middleware + protected endpoints |
appsettings.json | Add AzureAd configuration section |
*.csproj | Add Microsoft.Identity.Web NuGet package |