Skip to content

Commit 4fa824a

Browse files
committed
Add tennant validation middleware
1 parent 965cb0f commit 4fa824a

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using System.Text.RegularExpressions;
2+
3+
namespace NorthwindCRUD.Middlewares
4+
{
5+
public class TenantHeaderValidationMiddleware
6+
{
7+
private const string TenantHeaderKey = "X-Tenant-ID";
8+
9+
private readonly RequestDelegate _next;
10+
11+
public TenantHeaderValidationMiddleware(RequestDelegate next)
12+
{
13+
_next = next;
14+
}
15+
16+
public async Task InvokeAsync(HttpContext context)
17+
{
18+
var tenantHeader = context.Request.Headers[TenantHeaderKey].FirstOrDefault();
19+
20+
if (tenantHeader != null && !IsTenantValid(tenantHeader))
21+
{
22+
context.Response.StatusCode = StatusCodes.Status400BadRequest;
23+
await context.Response.WriteAsync($"Invalid format for Header {TenantHeaderKey}");
24+
return;
25+
}
26+
27+
await _next(context);
28+
}
29+
30+
private bool IsTenantValid(string tenantId)
31+
{
32+
return Regex.IsMatch(tenantId, "^[A-Za-z0-9-_]{0,40}$");
33+
}
34+
}
35+
}

NorthwindCRUD/Program.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
using Newtonsoft.Json.Converters;
1212
using NorthwindCRUD.Filters;
1313
using NorthwindCRUD.Helpers;
14+
using NorthwindCRUD.Middlewares;
1415
using NorthwindCRUD.Providers;
1516
using NorthwindCRUD.Services;
1617

@@ -132,7 +133,7 @@ public static void Main(string[] args)
132133

133134
// Necessary to detect if it's behind a load balancer, for example changing protocol, port or hostname
134135
app.UseForwardedHeaders();
135-
136+
app.UseMiddleware<TenantHeaderValidationMiddleware>();
136137
app.UseHttpsRedirection();
137138
app.UseDefaultFiles();
138139
app.UseStaticFiles();

0 commit comments

Comments
 (0)