DEV Community

Cover image for Advanced Techniques for Securing Minimal APIs in .NET 8
Leandro Veiga
Leandro Veiga

Posted on • Edited on

7

Advanced Techniques for Securing Minimal APIs in .NET 8

In this blog post, I’ll explore advanced techniques to secure your Minimal APIs in .NET 8. Security is critical for any API, and with the rise of Minimal APIs, it’s essential to understand how to protect them effectively. We’ll dive into JWT authentication, OAuth2, and custom authorization policies.

Why Security in Minimal APIs?

Minimal APIs are streamlined, but they still require the same level of security as any other API architecture. The challenge lies in ensuring that the simplicity of Minimal APIs doesn't compromise their security.

1. Implementing JWT Authentication in Minimal APIs

JSON Web Tokens (JWT) are a popular way to secure APIs due to their stateless nature and the ease of validating tokens. Here’s how to integrate JWT authentication into your .NET 8 Minimal API:

1.1. Install the JWT Bearer Dependency

Before configuring JWT authentication, you need to add the necessary NuGet package to your project. You can do this using the .NET CLI or through the NuGet Package Manager in Visual Studio.

Using .NET CLI:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Enter fullscreen mode Exit fullscreen mode

Using NuGet Package Manager:

  1. Right-click on your project in Solution Explorer.
  2. Select Manage NuGet Packages.
  3. Search for Microsoft.AspNetCore.Authentication.JwtBearer.
  4. Click Install.

1.2. Configure JWT Authentication in Program.cs

After installing the dependency, configure the JWT authentication services in your Program.cs file.

// Add JWT Authentication in Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer(options =>
    {
        options.Authority = "https://your-auth-server.com";
        options.Audience = "your-api";
    });
Enter fullscreen mode Exit fullscreen mode

Now, secure an endpoint by adding [Authorize] attribute:

var app = builder.Build();
app.MapGet("/secure-endpoint", [Authorize] () => "This is a secure endpoint")
    .RequireAuthorization();
Enter fullscreen mode Exit fullscreen mode

2. OAuth2 Integration for Third-Party Authentication

OAuth2 is widely used to allow third-party authentication from providers like Google, Facebook, or GitHub. In .NET 8, you can easily integrate it using libraries like Microsoft.AspNetCore.Authentication.OAuth:

builder.Services.AddAuthentication()
    .AddGoogle(options =>
    {
        options.ClientId = "your-client-id";
        options.ClientSecret = "your-client-secret";
    });
Enter fullscreen mode Exit fullscreen mode

Now users can authenticate using their Google account, providing seamless integration with your Minimal API.

3. Custom Authorization Policies

For more granular control, custom authorization policies let you define access rules beyond just roles or claims:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireClaim("role", "admin"));
});

app.MapGet("/admin", [Authorize(Policy = "AdminOnly")] () => "Admin Content");
Enter fullscreen mode Exit fullscreen mode

This ensures only users with a specific role or claim can access the /admin route.

4. Rate Limiting and IP Restriction

To prevent abuse, rate limiting can be a great tool. You can also restrict access to specific IP addresses:

app.Use(async (context, next) =>
{
    var ip = context.Connection.RemoteIpAddress;
    if (ip != null && ip.ToString() == "123.456.789.0")
    {
        await context.Response.WriteAsync("Access Denied");
    }
    else
    {
        await next();
    }
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

Securing Minimal APIs in .NET 8 doesn’t have to be complex. With JWT, OAuth2, and custom authorization policies, you can implement robust security mechanisms to protect your API while maintaining its simplicity. Remember to layer your security with techniques like rate limiting and IP restrictions to prevent abuse.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
nicowernli profile image
Nicolás Wernli • Edited

I guess step 1 would be installing JwtBearer

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Without this package I was getting an error builder.Services.AddAuthentication("Bearer")
.AddJwtBearer

Collapse
 
leandroveiga profile image
Leandro Veiga

Thank you for pointing that out!

I've updated the post to include the step for installing the package. I appreciate your feedback and I'm glad it helped resolve the error you encountered!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay