ASP.NET Core  

API Gateway Security Patterns for ASP.NET Core Microservices

As organizations adopt microservices architectures, securing communication between clients and distributed services becomes a critical challenge. Instead of exposing every microservice directly to the outside world, an API gateway acts as a single entry point that provides security, routing, load balancing, and observability.

This article explores common security patterns for API gateways in ASP.NET Core microservices and how to implement them effectively.

1. Why Use an API Gateway?

  • Single Entry Point → Clients interact with one endpoint instead of multiple microservices.

  • Security Centralization → Authentication, authorization, throttling, and logging are managed at the gateway.

  • Abstraction → Internal services are hidden, reducing attack surface.

  • Performance → Gateways can enable caching, compression, and aggregation.

Popular ASP.NET Core options:

  • YARP (Yet Another Reverse Proxy)

  • Ocelot API Gateway

  • Cloud solutions (Azure API Management, AWS API Gateway, Kong, NGINX).

2. Security Patterns for API Gateways

2.1. Authentication at the Gateway

Centralize authentication so individual microservices don’t have to implement it.

  • Use OAuth 2.0 + OpenID Connect with an Identity Provider (e.g., IdentityServer4, Azure AD, Auth0).

  • Gateway validates tokens and passes user claims to downstream services via headers.

Example with Ocelot and JWT Authentication:

builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.Authority = "https://identity.example.com";
        options.TokenValidationParameters = new()
        {
            ValidateAudience = false
        };
    });

builder.Services.AddOcelot();

Ocelot configuration (ocelot.json):

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/orders",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [{ "Host": "orderservice", "Port": 5001 }],
      "UpstreamPathTemplate": "/orders",
      "AuthenticationOptions": { "AuthenticationProviderKey": "Bearer" }
    }
  ]
}

2.2. Authorization Delegation

  • After authentication, enforce role-based or policy-based access control.

  • Example: only users with "Admin" role can access /admin routes.

  • Microservices receive only the claims they need, reducing leakage of sensitive identity data.

2.3. Rate Limiting & Throttling

Prevent abuse and DoS attacks by limiting requests per client.

Ocelot rate limiting example:

{
  "Routes": [
    {
      "UpstreamPathTemplate": "/api/products",
      "DownstreamPathTemplate": "/api/products",
      "RateLimitOptions": {
        "ClientWhitelist": [ "dev-client" ],
        "EnableRateLimiting": true,
        "Period": "1s",
        "PeriodTimespan": 1,
        "Limit": 5
      }
    }
  ]
}

This allows only 5 requests per second per client.

2.4. Input Validation and Request Filtering

The gateway can sanitize input before requests reach microservices.

  • Reject requests with malformed JSON or oversized payloads.

  • Enforce schema validation (e.g., using FluentValidation or JSON Schema).

  • Block dangerous headers or query parameters.

2.5. Centralized Logging & Monitoring

The API Gateway is the best place to implement:

  • Request/Response Logging (Serilog, ELK, Application Insights).

  • Correlation IDs to trace requests across services.

  • Metrics (Prometheus, OpenTelemetry).

app.Use(async (context, next) =>
{
    var correlationId = Guid.NewGuid().ToString();
    context.Response.Headers.Add("X-Correlation-ID", correlationId);
    await next();
});

2.6. TLS Termination and HTTPS Enforcement

  • Terminate SSL/TLS at the gateway (e.g., NGINX, YARP, Azure Front Door).

  • Enforce HTTPS redirection and HSTS headers.

app.UseHsts();
app.UseHttpsRedirection();

2.7. Caching and Response Shaping

  • Cache common responses at the gateway to reduce load.

  • Strip unnecessary headers before forwarding requests to internal services.

2.8. API Key Management (Optional)

For external APIs, issue API keys and validate them at the gateway.

  • Combine with OAuth2 for stronger security.

  • Rotate keys periodically.

3. API Gateway Security Architecture

A secure ASP.NET Core microservices setup typically looks like this:

[ Client Apps ] 
       |
       v
 [ API Gateway ]  --->  Authentication / Authorization
       |               --->  Rate Limiting / Input Validation
       v
 [ Internal Microservices ]

4. Best Practices Checklist

  • Use JWT/OAuth2 for authentication at the gateway.

  • Enforce role-based access control.

  • Apply rate limiting & throttling to prevent abuse.

  • Validate requests early (payload size, JSON schema).

  • Use TLS/HTTPS everywhere.

  • Implement centralized logging, monitoring, and correlation IDs.

  • Hide internal microservices from the public internet.

  • Consider a zero-trust approach where each microservice validates identity.

Conclusion

An API gateway is more than just a reverse proxy; it’s the security guard of your microservices architecture. By centralizing authentication, authorization, rate limiting, and monitoring, you significantly reduce the attack surface and improve resilience. ASP.NET Core developers can use tools like Ocelot or YARP to implement these patterns, while cloud-native solutions like Azure API Management provide enterprise-grade features out of the box.