Minimal APIs in .NET 6 bring a fresh, lightweight way to build HTTP services — but what about security? After all, even the smallest APIs often need authentication and authorization to protect sensitive endpoints.
Good news: Minimal APIs work seamlessly with ASP.NET Core’s built-in security features. In this post, we’ll explore how to add authentication and authorization to your Minimal APIs quickly and effectively.
🛠 Setting Up Authentication
For this example, we’ll add JWT Bearer token authentication, a common choice for APIs.
Step 1: Add Required NuGet Package
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Step 2: Configure Authentication in Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://demo.identityserver.io"; // Use your identity provider
options.Audience = "api1";
options.RequireHttpsMetadata = false;
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
🔐 Protecting Minimal API Endpoints
Once authentication and authorization are configured, you can protect your endpoints with the .RequireAuthorization()
method:
app.MapGet("/secret", () => "This is a secret message!")
.RequireAuthorization();
Only authenticated users with valid tokens can access this endpoint.
👤 Accessing User Information
You might want to access the current user inside your endpoint. Minimal APIs let you do this easily by injecting HttpContext
or the ClaimsPrincipal
:
app.MapGet("/profile", (ClaimsPrincipal user) =>
{
return $"Hello {user.Identity?.Name ?? "anonymous"}!";
}).RequireAuthorization();
⚙️ Adding Role-Based Authorization
Want to restrict endpoints to users with specific roles?
app.MapGet("/admin", () => "Welcome Admin!")
.RequireAuthorization(policy => policy.RequireRole("Admin"));
🛡️ Custom Policies and Claims
You can configure custom authorization policies during service registration:
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("MustBeEmployee", policy =>
policy.RequireClaim("EmployeeNumber"));
});
Then protect routes with:
app.MapGet("/employee-area", () => "Employee Content")
.RequireAuthorization("MustBeEmployee");
✅ Summary
Minimal APIs don’t compromise on security:
- You get full support for all ASP.NET Core authentication schemes.
- Use
.RequireAuthorization()
to secure routes easily. - Inject user info directly into endpoints.
- Apply role-based and custom policies like in traditional controllers.
Minimal APIs are perfect for quickly building secure services without the boilerplate.
Feel free to ask if you want future posts covering:
- Integration with IdentityServer or Azure AD
- Cookie-based auth with Minimal APIs
- Handling authorization failures and custom responses
- Testing secure Minimal APIs
Thanks for following along!