File tree Expand file tree Collapse file tree 2 files changed +37
-1
lines changed
Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 1111using Newtonsoft . Json . Converters ;
1212using NorthwindCRUD . Filters ;
1313using NorthwindCRUD . Helpers ;
14+ using NorthwindCRUD . Middlewares ;
1415using NorthwindCRUD . Providers ;
1516using 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 ( ) ;
You can’t perform that action at this time.
0 commit comments