English
Rate limiting
Step 1. Why throttle sign-in
Why. The account lockout of topic 8 stops guessing the password of one account: five wrong attempts lock it. It does not stop an attacker who tries one common password against thousands of accounts, nor a script that registers accounts in bulk. Those attacks come from few IP addresses in many requests. ASP.NET Core's rate limiter counts requests per partition — here per client IP — and rejects them above a limit.
Chatex throttles only the anonymous auth endpoints: 20 requests per IP per 60 seconds. A real user signs in a few times a day; the normal API, used by signed-in users, is not throttled.
Step 2. The policy
Do.
cs
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
namespace Chatex.Api.Infrastructure;
internal sealed class RateLimitingOptions
{
public const string Section = "RateLimiting";
/// <summary>Requests a client IP may make to the auth endpoints per window.</summary>
[Range(1, 1_000_000)]
public int AuthPermitLimit { get; set; } = 20;
[Range(1, 3600)]
public int AuthWindowSeconds { get; set; } = 60;
}
/// <summary>
/// Throttles the anonymous auth endpoints per client IP, so passwords cannot be guessed across many accounts and
/// accounts cannot be created in bulk. Behind Nginx the IP comes from <c>X-Forwarded-For</c> (UseForwardedHeaders).
/// </summary>
internal static class RateLimiting
{
public const string AuthPolicy = "auth";
public const string TooManyRequestsCode = "too_many_requests";
public static IServiceCollection AddChatexRateLimiting(this IServiceCollection services)
{
services.AddOptions<RateLimitingOptions>()
.BindConfiguration(RateLimitingOptions.Section)
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddRateLimiter(o =>
{
o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
o.OnRejected = WriteRejectionAsync;
});
services.AddOptions<RateLimiterOptions>()
.Configure<IOptions<RateLimitingOptions>>((limiter, options) =>
{
var settings = options.Value;
limiter.AddPolicy(AuthPolicy, context => RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = settings.AuthPermitLimit,
Window = TimeSpan.FromSeconds(settings.AuthWindowSeconds),
QueueLimit = 0,
}));
});
return services;
}
private static async ValueTask WriteRejectionAsync(OnRejectedContext context, CancellationToken cancellationToken)
{
var http = context.HttpContext;
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
http.Response.Headers.RetryAfter = ((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(CultureInfo.InvariantCulture);
}
var problems = http.RequestServices.GetRequiredService<IProblemDetailsService>();
await problems.WriteAsync(new ProblemDetailsContext
{
HttpContext = http,
ProblemDetails =
{
Status = StatusCodes.Status429TooManyRequests,
Detail = "Too many requests. Try again later.",
Extensions = { [ResultHttpExtensions.CodeExtension] = TooManyRequestsCode },
},
});
}
}RateLimitingOptionsmakes the limit configurable (the tests raise or lower it) and validated at start.- A fixed-window limiter per IP: at most
PermitLimitrequests per window, then rejections until the window ends.QueueLimit = 0rejects at once instead of making requests wait. - The policy reads the options at configuration time with
AddOptions<RateLimiterOptions>().Configure<IOptions<RateLimitingOptions>>(...)— the same technique as the JWT bearer options in topic 12. WriteRejectionAsyncanswers429 Too Many Requestsas Problem Details with the codetoo_many_requestsand aRetry-Afterheader with the seconds until the window ends. It usesIProblemDetailsService, so the body has the same shape as every other error.
Step 3. Throttle the auth group
Do. Add the policy to the auth group (the changed line in green):
cs
using System.Security.Claims;
using Chatex.Api.Contracts;
using Chatex.Api.Infrastructure;
using Chatex.Core.Auth;
using Chatex.Core.Common;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Chatex.Api.Endpoints;
internal static class AuthEndpoints
{
public static void MapAuthEndpoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/auth").WithTags("Auth").RequireRateLimiting(RateLimiting.AuthPolicy);
group.MapPost("/register", RegisterAsync).AllowAnonymous().WithName("Register")
.WithSummary("Creates an account and signs it in.");
group.MapPost("/login", LoginAsync).AllowAnonymous().WithName("Login")
.WithSummary("Signs in with a user name or email.");
group.MapPost("/refresh", RefreshAsync).AllowAnonymous().WithName("Refresh")
.WithSummary("Swaps the refresh token cookie for a new access token and cookie.");
group.MapPost("/logout", LogoutAsync).AllowAnonymous().WithName("Logout")
.WithSummary("Ends the session of the refresh token cookie.");
group.MapPost("/logout-all", LogoutAllAsync).WithName("LogoutAll")
.WithSummary("Ends every session of the signed-in user.");
}
private static async Task<Results<Ok<AuthResponse>, ProblemHttpResult>> RegisterAsync(
RegisterCommand command, IAuthService auth, HttpContext context, CancellationToken cancellationToken) =>
SignIn(await auth.RegisterAsync(command, context.GetClientInfo(), cancellationToken), context.Response);
private static async Task<Results<Ok<AuthResponse>, ProblemHttpResult>> LoginAsync(
LoginCommand command, IAuthService auth, HttpContext context, CancellationToken cancellationToken) =>
SignIn(await auth.LoginAsync(command, context.GetClientInfo(), cancellationToken), context.Response);
private static async Task<Results<Ok<AuthResponse>, ProblemHttpResult>> RefreshAsync(
IAuthService auth, HttpContext context, CancellationToken cancellationToken)
{
var token = RefreshTokenCookie.Read(context.Request);
var result = token is null
? AuthErrors.InvalidRefreshToken
: await auth.RefreshAsync(new RefreshCommand(token), context.GetClientInfo(), cancellationToken);
if (!result.IsSuccess)
{
RefreshTokenCookie.Clear(context.Response);
}
return SignIn(result, context.Response);
}
private static async Task<Results<NoContent, ProblemHttpResult>> LogoutAsync(
IAuthService auth, HttpContext context, CancellationToken cancellationToken)
{
var token = RefreshTokenCookie.Read(context.Request);
var result = token is null ? Result.Success : await auth.LogoutAsync(new RefreshCommand(token), cancellationToken);
RefreshTokenCookie.Clear(context.Response);
return result.ToNoContent();
}
private static async Task<Results<NoContent, ProblemHttpResult>> LogoutAllAsync(
ClaimsPrincipal user, IAuthService auth, HttpResponse response, CancellationToken cancellationToken)
{
var result = await auth.LogoutAllAsync(user.GetUserId(), cancellationToken);
if (result.IsSuccess)
{
RefreshTokenCookie.Clear(response);
}
return result.ToNoContent();
}
private static Results<Ok<AuthResponse>, ProblemHttpResult> SignIn(Result<AuthResult> result, HttpResponse response)
{
if (!result.IsSuccess)
{
return result.Error.ToProblem();
}
RefreshTokenCookie.Set(response, result.Value);
return TypedResults.Ok(AuthResponse.From(result.Value));
}
}One call on the group covers all five endpoints. The limiter itself is registered in AddApi and switched on with UseRateLimiter() in the next chapter.
The IP behind a proxy
In production every request reaches Kestrel from Nginx on 127.0.0.1. Without the next chapter's forwarded headers, all users would share one partition — and the 21st sign-in of the minute would lock out everybody.