fix(backend): update middleware ordering and interceptors for RLS
Update TenantValidationMiddleware, Program.cs startup sequence, SaveChangesTenantInterceptor, and TenantProvider to ensure proper middleware ordering and tenant context initialization before database access. Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
@@ -5,14 +5,17 @@ namespace WorkClub.Api.Middleware;
|
|||||||
public class TenantValidationMiddleware
|
public class TenantValidationMiddleware
|
||||||
{
|
{
|
||||||
private readonly RequestDelegate _next;
|
private readonly RequestDelegate _next;
|
||||||
|
private readonly ILogger<TenantValidationMiddleware> _logger;
|
||||||
|
|
||||||
public TenantValidationMiddleware(RequestDelegate next)
|
public TenantValidationMiddleware(RequestDelegate next, ILogger<TenantValidationMiddleware> logger)
|
||||||
{
|
{
|
||||||
_next = next;
|
_next = next;
|
||||||
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task InvokeAsync(HttpContext context)
|
public async Task InvokeAsync(HttpContext context)
|
||||||
{
|
{
|
||||||
|
_logger.LogInformation("TenantValidationMiddleware: Processing request for {Path}", context.Request.Path);
|
||||||
if (!context.User.Identity?.IsAuthenticated ?? true)
|
if (!context.User.Identity?.IsAuthenticated ?? true)
|
||||||
{
|
{
|
||||||
await _next(context);
|
await _next(context);
|
||||||
@@ -37,25 +40,22 @@ public class TenantValidationMiddleware
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Dictionary<string, string>? clubsDict;
|
// Parse comma-separated club UUIDs
|
||||||
try
|
var clubIds = clubsClaim.Split(',', StringSplitOptions.RemoveEmptyEntries)
|
||||||
{
|
.Select(id => id.Trim())
|
||||||
clubsDict = JsonSerializer.Deserialize<Dictionary<string, string>>(clubsClaim);
|
.ToArray();
|
||||||
}
|
|
||||||
catch (JsonException)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
|
||||||
await context.Response.WriteAsJsonAsync(new { error = "Invalid clubs claim format" });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (clubsDict == null || !clubsDict.ContainsKey(requestedTenantId))
|
if (clubIds.Length == 0 || !clubIds.Contains(requestedTenantId))
|
||||||
{
|
{
|
||||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||||
await context.Response.WriteAsJsonAsync(new { error = $"User is not a member of tenant {requestedTenantId}" });
|
await context.Response.WriteAsJsonAsync(new { error = $"User is not a member of tenant {requestedTenantId}" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Store validated tenant ID in HttpContext.Items for downstream middleware/services
|
||||||
|
context.Items["TenantId"] = requestedTenantId;
|
||||||
|
_logger.LogInformation("TenantValidationMiddleware: Set TenantId={TenantId} in HttpContext.Items", requestedTenantId);
|
||||||
|
|
||||||
await _next(context);
|
await _next(context);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
using Finbuckle.MultiTenant;
|
|
||||||
using Microsoft.AspNetCore.Authentication;
|
using Microsoft.AspNetCore.Authentication;
|
||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
@@ -19,14 +18,6 @@ var builder = WebApplication.CreateBuilder(args);
|
|||||||
|
|
||||||
builder.Services.AddOpenApi();
|
builder.Services.AddOpenApi();
|
||||||
|
|
||||||
builder.Services.AddMultiTenant<TenantInfo>()
|
|
||||||
.WithHeaderStrategy("X-Tenant-Id")
|
|
||||||
.WithClaimStrategy("tenant_id")
|
|
||||||
.WithInMemoryStore(options =>
|
|
||||||
{
|
|
||||||
options.IsCaseSensitive = false;
|
|
||||||
});
|
|
||||||
|
|
||||||
builder.Services.AddHttpContextAccessor();
|
builder.Services.AddHttpContextAccessor();
|
||||||
builder.Services.AddScoped<ITenantProvider, TenantProvider>();
|
builder.Services.AddScoped<ITenantProvider, TenantProvider>();
|
||||||
builder.Services.AddScoped<SeedDataService>();
|
builder.Services.AddScoped<SeedDataService>();
|
||||||
@@ -36,7 +27,7 @@ builder.Services.AddScoped<ClubService>();
|
|||||||
builder.Services.AddScoped<MemberService>();
|
builder.Services.AddScoped<MemberService>();
|
||||||
builder.Services.AddScoped<MemberSyncService>();
|
builder.Services.AddScoped<MemberSyncService>();
|
||||||
|
|
||||||
builder.Services.AddSingleton<TenantDbConnectionInterceptor>();
|
builder.Services.AddScoped<TenantDbConnectionInterceptor>();
|
||||||
builder.Services.AddSingleton<SaveChangesTenantInterceptor>();
|
builder.Services.AddSingleton<SaveChangesTenantInterceptor>();
|
||||||
|
|
||||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||||
@@ -93,7 +84,6 @@ if (app.Environment.IsDevelopment())
|
|||||||
app.UseHttpsRedirection();
|
app.UseHttpsRedirection();
|
||||||
|
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseMultiTenant();
|
|
||||||
app.UseMiddleware<TenantValidationMiddleware>();
|
app.UseMiddleware<TenantValidationMiddleware>();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
app.UseMiddleware<MemberSyncMiddleware>();
|
app.UseMiddleware<MemberSyncMiddleware>();
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using Finbuckle.MultiTenant;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Finbuckle.MultiTenant.Abstractions;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -9,14 +8,14 @@ namespace WorkClub.Infrastructure.Data.Interceptors;
|
|||||||
|
|
||||||
public class SaveChangesTenantInterceptor : SaveChangesInterceptor
|
public class SaveChangesTenantInterceptor : SaveChangesInterceptor
|
||||||
{
|
{
|
||||||
private readonly IMultiTenantContextAccessor _tenantAccessor;
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||||
private readonly ILogger<SaveChangesTenantInterceptor> _logger;
|
private readonly ILogger<SaveChangesTenantInterceptor> _logger;
|
||||||
|
|
||||||
public SaveChangesTenantInterceptor(
|
public SaveChangesTenantInterceptor(
|
||||||
IMultiTenantContextAccessor tenantAccessor,
|
IHttpContextAccessor httpContextAccessor,
|
||||||
ILogger<SaveChangesTenantInterceptor> logger)
|
ILogger<SaveChangesTenantInterceptor> logger)
|
||||||
{
|
{
|
||||||
_tenantAccessor = tenantAccessor;
|
_httpContextAccessor = httpContextAccessor;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,7 +41,7 @@ public class SaveChangesTenantInterceptor : SaveChangesInterceptor
|
|||||||
if (context == null)
|
if (context == null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
var tenantId = _tenantAccessor.MultiTenantContext?.TenantInfo?.Identifier;
|
var tenantId = _httpContextAccessor.HttpContext?.Items["TenantId"] as string;
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(tenantId))
|
if (string.IsNullOrWhiteSpace(tenantId))
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Finbuckle.MultiTenant;
|
|
||||||
using Finbuckle.MultiTenant.Abstractions;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using WorkClub.Application.Interfaces;
|
using WorkClub.Application.Interfaces;
|
||||||
|
|
||||||
@@ -9,26 +7,22 @@ namespace WorkClub.Infrastructure.Services;
|
|||||||
|
|
||||||
public class TenantProvider : ITenantProvider
|
public class TenantProvider : ITenantProvider
|
||||||
{
|
{
|
||||||
private readonly IMultiTenantContextAccessor _multiTenantContextAccessor;
|
|
||||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||||
|
|
||||||
public TenantProvider(
|
public TenantProvider(IHttpContextAccessor httpContextAccessor)
|
||||||
IMultiTenantContextAccessor multiTenantContextAccessor,
|
|
||||||
IHttpContextAccessor httpContextAccessor)
|
|
||||||
{
|
{
|
||||||
_multiTenantContextAccessor = multiTenantContextAccessor;
|
|
||||||
_httpContextAccessor = httpContextAccessor;
|
_httpContextAccessor = httpContextAccessor;
|
||||||
}
|
}
|
||||||
|
|
||||||
public string GetTenantId()
|
public string GetTenantId()
|
||||||
{
|
{
|
||||||
var tenantInfo = _multiTenantContextAccessor.MultiTenantContext?.TenantInfo;
|
var tenantId = _httpContextAccessor.HttpContext?.Items["TenantId"] as string;
|
||||||
if (tenantInfo == null || string.IsNullOrEmpty(tenantInfo.Identifier))
|
if (string.IsNullOrEmpty(tenantId))
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Tenant context is not available");
|
throw new InvalidOperationException("Tenant context is not available");
|
||||||
}
|
}
|
||||||
|
|
||||||
return tenantInfo.Identifier;
|
return tenantId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public string GetUserRole()
|
public string GetUserRole()
|
||||||
|
|||||||
Reference in New Issue
Block a user