LESSON 14 OF 15

Rate Limiting and HTTP Security Configuration

Learn how to configure rate limiting, HTTPS, HSTS, secure cookies and essential HTTP security headers in ASP.NET Core applications.

35 dk 87

Introduction

The previous lessons covered identity validation, roles, claims, JWT creation and endpoint authorization. However, an authenticated client can still call an API too frequently, trigger expensive queries or repeatedly submit credentials to a login endpoint. Authentication alone does not control traffic volume or transport security.

In this lesson, we will use ASP.NET Core's built-in rate limiting middleware to control access to API endpoints. We will then configure HTTPS, HSTS, cookie security options and several essential HTTP security headers. The goal is not to memorize one universal configuration, but to select policies based on endpoint cost, client type and deployment architecture.

What is rate limiting?

Rate limiting restricts the number of requests accepted during a period of time or the number of requests processed concurrently. It is not a replacement for network-level DDoS protection, but it is useful for reducing application-level abuse, accidental traffic spikes and resource exhaustion. Login, password reset, search, report generation and file upload operations are common candidates.

Common algorithms

  • Fixed window: A counter is maintained for a fixed interval, such as 100 requests per 60 seconds. It is simple, but requests can cluster at the end and beginning of adjacent windows.
  • Sliding window: The time window is divided into segments and moves continuously. This reduces the sharp boundary effect of a fixed window.
  • Token bucket: Tokens are added to a bucket at regular intervals. Each request consumes a token. The algorithm allows controlled short bursts while limiting the long-term average rate.
  • Concurrency: This limits the number of operations running at the same time rather than the total number of requests in a period. It can be useful for long-running reports or file processing.

When selecting an algorithm, consider CPU, memory, database, network and external-service costs rather than looking only at request counts. ASP.NET Core provides built-in fixed-window, sliding-window, token-bucket and concurrency limiter options. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit?view=aspnetcore-10.0&utm_source=openai))

Registering rate limiting

First, register the rate limiting services and add the middleware to the request pipeline. This example defines three named policies: a strict fixed window for login, a sliding window for search, and a token bucket for general API traffic.

using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddRateLimiter(options =>
{
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;

    options.AddFixedWindowLimiter("login", limiter =>
    {
        limiter.PermitLimit = 5;
        limiter.Window = TimeSpan.FromMinutes(1);
        limiter.QueueLimit = 0;
    });

    options.AddSlidingWindowLimiter("search", limiter =>
    {
        limiter.PermitLimit = 30;
        limiter.Window = TimeSpan.FromMinutes(1);
        limiter.SegmentsPerWindow = 6;
        limiter.QueueLimit = 0;
    });

    options.AddTokenBucketLimiter("api", limiter =>
    {
        limiter.TokenLimit = 60;
        limiter.TokensPerPeriod = 20;
        limiter.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
        limiter.AutoReplenishment = true;
        limiter.QueueLimit = 0;
    });
});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.Run();

Named policies must be explicitly applied to endpoints. For endpoint-specific policies, place UseRateLimiter after routing. A global limiter can be placed differently, but keeping the middleware after routing makes endpoint policy behavior easier to understand. In ASP.NET Core 8 and later, the rate limiting services must be registered with AddRateLimiter before the middleware is used. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit?view=aspnetcore-10.0&utm_source=openai))

Applying policies to endpoints

For controller-based APIs, use the EnableRateLimiting attribute.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;

[ApiController]
[Route("api/account")]
public sealed class AccountController : ControllerBase
{
    [HttpPost("login")]
    [AllowAnonymous]
    [EnableRateLimiting("login")]
    public IActionResult Login(LoginRequest request)
    {
        return Ok(new { message = "Login example" });
    }
}

[ApiController]
[Route("api/products")]
[Authorize]
public sealed class ProductsController : ControllerBase
{
    [HttpGet("search")]
    [EnableRateLimiting("search")]
    public IActionResult Search([FromQuery] string term)
    {
        return Ok(new[] { term });
    }

    [HttpGet]
    [EnableRateLimiting("api")]
    public IActionResult GetAll()
    {
        return Ok(Array.Empty<object>());
    }
}

public sealed record LoginRequest(string Email, string Password);

With Minimal APIs, apply the same policy by calling RequireRateLimiting:

app.MapGet("/api/products", () => Results.Ok("products"))
   .RequireAuthorization()
   .RequireRateLimiting("api");

Returning a useful 429 response

When a limit is exceeded, the client should receive 429 Too Many Requests. A Retry-After header can tell clients when they may try again. This is particularly useful for mobile applications, scheduled jobs and background workers.

builder.Services.AddRateLimiter(options =>
{
    options.OnRejected = async (context, cancellationToken) =>
    {
        context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
        context.HttpContext.Response.Headers.RetryAfter = "60";
        await context.HttpContext.Response.WriteAsJsonAsync(
            new { error = "too_many_requests" }, cancellationToken);
    };
});

The actual retry interval should reflect the selected algorithm and policy. A hard-coded value of 60 is only illustrative. Queuing also requires care: queued requests still consume application resources. For login and other abuse-prone endpoints, a queue limit of zero is often preferable to allowing an attacker to build a large backlog.

Partitioning: who receives the limit?

A single global counter allows one client to consume capacity for every other client. Partitioning divides counters by a key such as IP address, user identity, API key or tenant identifier. For example, an anonymous request can use an IP-based partition while an authenticated request can use a user-based partition.

builder.Services.AddRateLimiter(options =>
{
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
    {
        var key = httpContext.User.Identity?.IsAuthenticated == true
            ? $"user:{httpContext.User.Identity.Name}"
            : $"ip:{httpContext.Connection.RemoteIpAddress}";

        return RateLimitPartition.GetFixedWindowLimiter(
            key,
            _ => new FixedWindowRateLimiterOptions
            {
                PermitLimit = 100,
                Window = TimeSpan.FromMinutes(1),
                QueueLimit = 0,
                AutoReplenishment = true
            });
    });
});

When the application runs behind a proxy or load balancer, verify that the client IP is obtained correctly. Do not make security decisions from an untrusted X-Forwarded-For value. Forwarded headers should be enabled only for known, trusted proxies; otherwise a client may be able to manipulate the apparent source address.

HTTPS and HSTS

Sending passwords, cookies or bearer tokens over HTTP can expose credentials and tokens at the transport layer. For web applications, UseHttpsRedirection can redirect HTTP requests to HTTPS, while UseHsts can tell supporting browsers to use HTTPS for future requests in production.

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();

HSTS takes effect in a browser after a successful HTTPS response and primarily controls browser behavior. Mobile and desktop clients may not process the header in the same way. For APIs, relying only on a redirect can be unsafe because some clients do not follow redirects and a sensitive first request may already have been sent over HTTP. A stronger API deployment can listen only on HTTPS or reject HTTP requests. If a reverse proxy terminates HTTPS, clearly define whether the proxy or the application owns redirection and HSTS responsibilities. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-10.0&utm_source=openai))

Cookie security options

For cookie authentication, HttpOnly prevents ordinary JavaScript from reading the cookie, Secure restricts transmission to HTTPS, and SameSite controls cross-site sending behavior.

builder.Services.ConfigureApplicationCookie(options =>
{
    options.Cookie.Name = "CourseApp.Auth";
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
    options.SlidingExpiration = true;
});

SameSite=Lax is a reasonable starting point for many traditional MVC applications. Cross-site iframes, selected OAuth flows and cross-domain cookie scenarios may require a different design and careful testing. Cookie settings do not replace CSRF protection. State-changing MVC operations should also use an appropriate antiforgery strategy.

Essential HTTP security headers

ASP.NET Core does not automatically solve every header policy with one setting. The application or reverse proxy should evaluate at least the following headers:

HeaderPurpose
Strict-Transport-SecurityInstructs a browser to use HTTPS for the domain.
X-Content-Type-Options: nosniffReduces content-type sniffing behavior.
Content-Security-PolicyRestricts permitted resource and script sources.
Referrer-PolicyControls how much referrer information is sent.
Permissions-PolicyRestricts browser features such as camera and microphone access.

An example middleware is shown below:

app.Use(async (context, next) =>
{
    context.Response.Headers["X-Content-Type-Options"] = "nosniff";
    context.Response.Headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
    context.Response.Headers["Permissions-Policy"] = "camera=(), microphone=()";
    context.Response.Headers["Content-Security-Policy"] =
        "default-src 'self'; object-src 'none'; frame-ancestors 'none';";

    await next();
});

Content Security Policy must match the application's JavaScript, CSS, font and third-party service requirements. Adding an arbitrary CSP can break existing pages. Begin by observing the application's resource usage, then tighten the policy incrementally. In an API-only project, CSP may have limited value, but HTTPS, CORS, cookie handling and non-disclosing error responses remain important.

Common mistakes

  • Using rate limiting as authentication: A limiter controls traffic; it does not establish identity.
  • Using one limit for every endpoint: A simple GET request and a database-heavy report do not have the same cost.
  • Trusting only IP addresses: Users behind NAT may share a limit, and proxy headers can be misconfigured.
  • Enabling HSTS during development: Browser caching can make local HTTP development unexpectedly difficult.
  • Redirecting every API HTTP request: Some clients may not follow redirects, and sensitive data may already have been sent over HTTP.
  • Omitting Secure cookies: A cookie may travel over the network if HTTPS is unexpectedly disabled.
  • Returning an empty 429 response: Without a consistent error body or retry guidance, clients may retry too aggressively.

Practice exercise

  1. Configure a fixed-window login policy allowing five requests per minute.
  2. Apply a sliding-window policy to a protected search endpoint.
  3. Return a JSON error body and a Retry-After header when a request is rejected.
  4. Configure cookie authentication with HttpOnly, Secure and an appropriate SameSite value.
  5. Enable HSTS and HTTPS redirection outside the Development environment.
  6. Use Swagger, a browser and an API client to test rejected requests, HTTP access and response cookies.

Conclusion

Rate limiting adds an important application-level defense against abuse and uncontrolled resource consumption. Fixed windows are simple, sliding windows provide smoother time-based control, and token buckets support controlled bursts. Partitioning allows limits to be separated by user, IP, API key or tenant.

HTTPS and secure cookie settings protect credentials and tokens while they are transported. HSTS helps browsers prefer HTTPS in the future, but API deployments should not rely on HSTS alone. Listening only on HTTPS or rejecting HTTP is stronger for sensitive API traffic. In the final lesson, we will turn these techniques into a production-readiness security checklist and review the complete authentication architecture.

Sources