Add RateLimiting For API
This commit is contained in:
@@ -34,7 +34,8 @@ namespace BoredCareers.Controllers {
|
|||||||
await _databaseService.SetAccount(test);
|
await _databaseService.SetAccount(test);
|
||||||
|
|
||||||
List<Claim> claims = new List<Claim>() {
|
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(
|
await HttpContext.SignInAsync(
|
||||||
|
|||||||
+22
-1
@@ -2,7 +2,10 @@ using Microsoft.AspNetCore.Authentication.Cookies;
|
|||||||
using BoredCareers.Controllers.Payment;
|
using BoredCareers.Controllers.Payment;
|
||||||
using BoredCareers.Services;
|
using BoredCareers.Services;
|
||||||
using BoredCareers.Services.DatabaseService;
|
using BoredCareers.Services.DatabaseService;
|
||||||
|
using System.Threading.RateLimiting;
|
||||||
|
using Microsoft.AspNetCore.RateLimiting;
|
||||||
using Stripe;
|
using Stripe;
|
||||||
|
using System.Security.Claims;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
@@ -94,6 +97,24 @@ builder.Services.AddCors( o => o.AddDefaultPolicy( builder => {
|
|||||||
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); // No CORS
|
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
|
// Pages Service
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
builder.Services.AddRazorPages();
|
builder.Services.AddRazorPages();
|
||||||
@@ -113,7 +134,7 @@ app.UseCors();
|
|||||||
app.UseRouting();
|
app.UseRouting();
|
||||||
|
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.MapControllers();
|
app.MapControllers().RequireRateLimiting("perUserPolicy");
|
||||||
|
|
||||||
app.MapFallbackToFile("index.html");
|
app.MapFallbackToFile("index.html");
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user