Add RateLimiting For API

This commit is contained in:
derek.holloway
2025-07-15 14:38:02 -07:00
parent b93eb3ad21
commit c04877464a
2 changed files with 26 additions and 4 deletions
@@ -34,7 +34,8 @@ namespace BoredCareers.Controllers {
await _databaseService.SetAccount(test);
List<Claim> claims = new List<Claim>() {
new Claim("ID", test.ID.ToString())
new Claim("ID", test.ID.ToString()),
new Claim(ClaimTypes.NameIdentifier, test.ID.ToString())
};
await HttpContext.SignInAsync(
+24 -3
View File
@@ -2,7 +2,10 @@ using Microsoft.AspNetCore.Authentication.Cookies;
using BoredCareers.Controllers.Payment;
using BoredCareers.Services;
using BoredCareers.Services.DatabaseService;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
using Stripe;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
@@ -90,9 +93,27 @@ builder.Services.AddAuthentication( options => {
options.SlidingExpiration = true;
});
builder.Services.AddCors( o => o.AddDefaultPolicy( builder => {
builder.Services.AddCors(o => o.AddDefaultPolicy(builder => {
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); // No CORS
} ) );
}));
builder.Services.AddRateLimiter(options => {
options.AddPolicy("PerUserPolicy", httpContext => {
// Identify the user (assumes authenticated user with NameIdentifier claim)
var userId = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value
?? httpContext.User.Identity?.Name
?? httpContext.Connection.RemoteIpAddress?.ToString();
return RateLimitPartition.GetTokenBucketLimiter(userId, key => new TokenBucketRateLimiterOptions {
TokenLimit = 10, // max 10 requests
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
ReplenishmentPeriod = TimeSpan.FromSeconds(15),
TokensPerPeriod = 2,
AutoReplenishment = true
});
});
});
// Pages Service
builder.Services.AddControllers();
@@ -113,7 +134,7 @@ app.UseCors();
app.UseRouting();
app.UseAuthentication();
app.MapControllers();
app.MapControllers().RequireRateLimiting("perUserPolicy");
app.MapFallbackToFile("index.html");