dotnet-multi-tenant
Skill1 starsChanged 7 months agoMITView on GitHub
Implements Multi-Tenant pattern in .NET APIs with per-tenant database isolation, per-tenant JWT secrets, ACL layer with automatic TenantId propagation via DelegatingHandler, and dynamic DbContext factory. Covers TenantMiddleware, TenantContext, TenantResolver, TenantHeaderHandler, TenantDbContextFactory, and dynamic JWT configuration.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- emaginebr/AvaBotword for word, first seen Apr 8, 2026
Other versions1 project uses a version of this.
Word for word · 1
- emaginebr/AvaBot★ 2100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository39 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- readme-generatorSkill
- add-react-i18nSkill
- band-album-campaignSkill
- band-music-reflectionSkill
- band-streaming-launchSkill
- ckm:banner-designSkill
- ckm:brandSkill
- deploy-prodSkill
- ckm:designSkill
- ckm:design-systemSkill
- docker-compose-configSkill
- doc-managerSkill
- dotnet-architectureSkill
- dotnet-doc-controllerSkill
- dotnet-envSkill
- dotnet-fluent-validationSkill
- dotnet-graphqlSkill
- dotnet-test-apiSkill
- dotnet-testSkill
- frontend-designSkill
- gitversionSkill
- maui-architectureSkill
- mermaid-chartSkill
- nauth-guideSkill
- nnews-guideSkill
- react-alertSkill
- react-architectureSkill
- react-archSkill
- react-modalSkill
- readme-generatorSkill
- ckm:slidesSkill
- social-media-assetsSkill
- social-media-schedulingSkill
- social-post-authoringSkill
- ckm:ui-stylingSkill
- ui-ux-pro-maxSkill
- wsl-dockerSkill
- ztools-guideSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 338
Read JwtSecret via IConfiguration["Tenants:{tenantId}:JwtSecret"]
- Very specific: line 489
Security: never accept TenantId from request body — only from header or JWT
- Distinctive: line 491
ACL: do not directly reference infrastructure projects — use interfaces
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
.NET Multi-Tenant API Implementation Guide
You are an expert assistant that helps developers implement the Multi-Tenant pattern in .NET APIs. You guide the user through all required components: tenant resolution, JWT per-tenant, database isolation, and ACL propagation.
Input
The user will describe what to create or modify: $ARGUMENTS
Before generating code:
- Read the solution structure — Identify all projects/layers (API, ACL, Application, Domain, Infra)
- Find existing patterns — Check for existing authentication, DbContext, and HttpClient registrations
- Read
appsettings.json— Check for existing tenant configuration - Read
Program.csorStartup.cs— Understand current DI and middleware setup - Identify existing DbContext — You must NOT modify Models, DTOs, or DbContext structure
Architecture Overview
Multi-Tenant Resolution Flow
┌─────────────────────────────────────────────────────────┐
│ API Layer │
│ │
│ ┌─────────────────┐ ┌────────────────────────────┐ │
│ │ TenantMiddleware │───▶│ HttpContext.Items["TenantId"]│ │
│ │ (runs before │ └────────────────────────────┘ │
│ │ auth pipeline) │ │
│ └─────────────────┘ │
│ │
│ Unauthenticated endpoints → Header: X-Tenant-Id │
│ Authenticated endpoints → JWT claim: tenant_id │
└─────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ ACL Layer │
│ │
│ ┌──────────────────────┐ ┌────────────────────────┐ │
│ │ TenantHeaderHandler │──▶│ Injects X-Tenant-Id │ │
│ │ (DelegatingHandler) │ │ into ALL HttpClient │ │
│ │ │ │ requests automatically │ │
│ └──────────────────────┘ └────────────────────────┘ │
│ │
│ TenantId source: appsettings.json → Tenant:DefaultId │
│ NEVER passed as method parameter │
└─────────────────────────────────────────────────────────┘Per-Tenant Isolation
| Concern | Strategy |
| Database | Separate ConnectionString per tenant |
| Authentication | Separate JwtSecret per tenant |
| Tenant Resolution (API) | Header or JWT claim |
| Tenant Resolution (ACL) | appsettings.json config |
Configuration — appsettings.json
Each tenant has its own ConnectionString and JwtSecret:
{
"Tenant": {
"DefaultTenantId": "tenant-a"
},
"Tenants": {
"tenant-a": {
"ConnectionString": "Server=srv1;Database=TenantA_DB;User Id=sa;Password=***;",
"JwtSecret": "super-secret-key-tenant-a-256bits"
},
"tenant-b": {
"ConnectionString": "Server=srv2;Database=TenantB_DB;User Id=sa;Password=***;",
"JwtSecret": "super-secret-key-tenant-b-256bits"
}
}
}Components to Implement
1. ITenantContext / TenantContext (Application Layer)
Provides the current tenant ID within the API request scope.
File: Application/Interfaces/ITenantContext.cs
public interface ITenantContext
{
string TenantId { get; }
}File: Application/Services/TenantContext.cs
public class TenantContext : ITenantContext
{
private readonly IHttpContextAccessor _httpContextAccessor;
public TenantContext(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public string TenantId
{
get
{
var context = _httpContextAccessor.HttpContext;
if (context == null)
throw new InvalidOperationException("No active HTTP context.");
// Authenticated: resolve from JWT claim
var claimTenant = context.User?.FindFirst("tenant_id")?.Value;
if (!string.IsNullOrEmpty(claimTenant))
return claimTenant;
// Unauthenticated: resolve from middleware-set item
if (context.Items.TryGetValue("TenantId", out var headerTenant)
&& headerTenant is string tenantStr
&& !string.IsNullOrEmpty(tenantStr))
return tenantStr;
throw new InvalidOperationException(
"TenantId could not be resolved from JWT claim or X-Tenant-Id header.");
}
}
}Registration: Scoped
2. TenantMiddleware (API Layer)
Runs before the authentication middleware. Extracts X-Tenant-Id from the request header and stores it in HttpContext.Items.
File: Api/Middlewares/TenantMiddleware.cs
public class TenantMiddleware
{
private readonly RequestDelegate _next;
public TenantMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Headers.TryGetValue("X-Tenant-Id", out var tenantId)
&& !string.IsNullOrWhiteSpace(tenantId))
{
context.Items["TenantId"] = tenantId.ToString();
}
await _next(context);
}
}Registration in Program.cs:
// MUST be registered BEFORE UseAuthentication / UseAuthorization
app.UseMiddleware<TenantMiddleware>();
app.UseAuthentication();
app.UseAuthorization();3. ITenantResolver / TenantResolver (ACL Layer)
Resolves tenant configuration from appsettings.json. Used by the ACL layer only.
File: ACL/Interfaces/ITenantResolver.cs
public interface ITenantResolver
{
string TenantId { get; }
string ConnectionString { get; }
string JwtSecret { get; }
}File: ACL/Services/TenantResolver.cs
public class TenantResolver : ITenantResolver
{
private readonly IConfiguration _configuration;
public TenantResolver(IConfiguration configuration)
{
_configuration = configuration;
}
public string TenantId
{
get
{
var tenantId = _configuration["Tenant:DefaultTenantId"];
if (string.IsNullOrEmpty(tenantId))
throw new InvalidOperationException(
"Tenant:DefaultTenantId is not configured in appsettings.json.");
return tenantId;
}
}
public string ConnectionString
{
get
{
var cs = _configuration[$"Tenants:{TenantId}:ConnectionString"];
if (string.IsNullOrEmpty(cs))
throw new InvalidOperationException(
$"ConnectionString not found for tenant '{TenantId}'. " +
$"Expected key: Tenants:{TenantId}:ConnectionString");
return cs;
}
}
public string JwtSecret
{
get
{
var secret = _configuration[$"Tenants:{TenantId}:JwtSecret"];
if (string.IsNullOrEmpty(secret))
throw new InvalidOperationException(
$"JwtSecret not found for tenant '{TenantId}'. " +
$"Expected key: Tenants:{TenantId}:JwtSecret");
return secret;
}
}
}Registration: Scoped
4. TenantHeaderHandler (ACL Layer)
A DelegatingHandler that automatically injects the X-Tenant-Id header into every HTTP request made by ACL HttpClient instances. The TenantId is never passed as a method parameter.
File: ACL/Handlers/TenantHeaderHandler.cs
public class TenantHeaderHandler : DelegatingHandler
{
private readonly IConfiguration _configuration;
public TenantHeaderHandler(IConfiguration configuration)
{
_configuration = configuration;
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var tenantId = _configuration["Tenant:DefaultTenantId"];
if (!string.IsNullOrEmpty(tenantId))
request.Headers.TryAddWithoutValidation("X-Tenant-Id", tenantId);
return await base.SendAsync(request, cancellationToken);
}
}Registration: Transient
services.AddTransient<TenantHeaderHandler>();
// Register for EVERY ACL HttpClient:
services.AddHttpClient<IMyAclService, MyAclService>()
.AddHttpMessageHandler<TenantHeaderHandler>();5. Dynamic JWT Configuration
Since each tenant has its own JwtSecret, JWT validation cannot use a static key. Use IssuerSigningKeyResolver to dynamically resolve the signing key based on the tenant_id claim in the token.
JWT Validation Setup (in Program.cs or auth config):
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKeyResolver = (token, securityToken, kid, parameters) =>
{
var handler = new JwtSecurityTokenHandler();
var jwt = handler.ReadJwtToken(token);
var tenantId = jwt.Claims
.FirstOrDefault(c => c.Type == "tenant_id")?.Value;
var secret = configuration[$"Tenants:{tenantId}:JwtSecret"];
if (string.IsNullOrEmpty(secret))
throw new SecurityTokenException(
$"JwtSecret not found for tenant: {tenantId}");
return new[]
{
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret))
};
},
ValidateIssuer = false,
ValidateAudience = false
};
});Token Generation (Login):
- Resolve
TenantIdfromX-Tenant-Idheader - Read
JwtSecretviaIConfiguration["Tenants:{tenantId}:JwtSecret"] - Include
tenant_idclaim in the payload - Sign with the tenant's
JwtSecret
public interface ITokenService
{
string GenerateToken(string tenantId, string userId, string email);
}
public class TokenService : ITokenService
{
private readonly IConfiguration _configuration;
public TokenService(IConfiguration configuration)
{
_configuration = configuration;
}
public string GenerateToken(string tenantId, string userId, string email)
{
var secret = _configuration[$"Tenants:{tenantId}:JwtSecret"]
?? throw new InvalidOperationException(
$"JwtSecret not found for tenant: {tenantId}");
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim("tenant_id", tenantId),
new Claim(ClaimTypes.NameIdentifier, userId),
new Claim(ClaimTypes.Email, email)
};
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.UtcNow.AddHours(8),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}6. ITenantDbContextFactory / TenantDbContextFactory (ACL Layer)
Creates DbContext instances at runtime using the tenant-specific ConnectionString. Does NOT modify the existing AppDbContext.
File: ACL/Interfaces/ITenantDbContextFactory.cs
public interface ITenantDbContextFactory
{
AppDbContext CreateDbContext();
}File: ACL/Services/TenantDbContextFactory.cs
public class TenantDbContextFactory : ITenantDbContextFactory
{
private readonly ITenantResolver _tenantResolver;
public TenantDbContextFactory(ITenantResolver tenantResolver)
{
_tenantResolver = tenantResolver;
}
public AppDbContext CreateDbContext()
{
var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
optionsBuilder.UseSqlServer(_tenantResolver.ConnectionString);
return new AppDbContext(optionsBuilder.Options);
}
}Registration: Scoped
7. Dependency Injection — Full Registration
// --- HTTP Context ---
services.AddHttpContextAccessor();
// --- Tenant Services ---
services.AddScoped<ITenantContext, TenantContext>();
services.AddScoped<ITenantResolver, TenantResolver>();
services.AddScoped<ITenantDbContextFactory, TenantDbContextFactory>();
services.AddScoped<ITokenService, TokenService>();
// --- TenantHeaderHandler ---
services.AddTransient<TenantHeaderHandler>();
// --- DbContext via Factory ---
services.AddScoped(sp =>
sp.GetRequiredService<ITenantDbContextFactory>().CreateDbContext());
// --- ACL HttpClients (add handler to ALL) ---
services.AddHttpClient<IMyAclService, MyAclService>()
.AddHttpMessageHandler<TenantHeaderHandler>();
// Repeat for every ACL HttpClient:
// services.AddHttpClient<IOtherAclService, OtherAclService>()
// .AddHttpMessageHandler<TenantHeaderHandler>();
// --- JWT Authentication ---
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => { /* IssuerSigningKeyResolver as shown above */ });Expected Folder Structure
src/
├── Api/
│ ├── Middlewares/
│ │ └── TenantMiddleware.cs
│ └── Program.cs
├── ACL/
│ ├── Handlers/
│ │ └── TenantHeaderHandler.cs
│ ├── Interfaces/
│ │ ├── ITenantResolver.cs
│ │ └── ITenantDbContextFactory.cs
│ └── Services/
│ ├── TenantResolver.cs
│ └── TenantDbContextFactory.cs
└── Application/
├── Interfaces/
│ └── ITenantContext.cs
└── Services/
└── TenantContext.csMandatory Constraints
- Do NOT modify Models, DTOs,
DbSets, orOnModelCreatingin the existingAppDbContext - Do NOT use static
AddDbContext— use the scoped factory instead - Do NOT use a global/static
JwtSecret— each tenant has its own - In the ACL, NEVER pass
TenantIdas a method parameter — propagate exclusively viaX-Tenant-Idheader throughTenantHeaderHandler - Security: never accept
TenantIdfrom request body — only from header or JWT - Security: in
IssuerSigningKeyResolver, only read the token to extracttenant_id— signature validation occurs immediately after with the resolved key - ACL: do not directly reference infrastructure projects — use interfaces
- Lifecycle: tenant services are
Scoped;TenantHeaderHandlerisTransient
Usage Examples
ACL Service — No tenant parameter; header injected automatically
public class ProductAclService : IProductAclService
{
private readonly HttpClient _httpClient;
public ProductAclService(HttpClient httpClient)
{
_httpClient = httpClient; // TenantHeaderHandler already adds X-Tenant-Id
}
public async Task<List<ProductDto>> GetAllAsync()
{
return await _httpClient.GetFromJsonAsync<List<ProductDto>>("api/products");
}
}API — Unauthenticated endpoint
[AllowAnonymous]
[HttpGet("public/products")]
public async Task<IActionResult> GetPublicProducts()
{
// TenantId resolved from X-Tenant-Id header
var data = await _service.GetAllAsync();
return Ok(data);
}API — Authenticated endpoint
[Authorize]
[HttpGet("private/products")]
public async Task<IActionResult> GetPrivateProducts()
{
// TenantId resolved from JWT claim
var data = await _service.GetAllAsync();
return Ok(data);
}Deliverables Checklist
TenantMiddleware.csITenantContext.csandTenantContext.csITenantResolver.csandTenantResolver.cswithTenantId,ConnectionString, andJwtSecretTenantHeaderHandler.cs— DelegatingHandler injectingX-Tenant-Idinto all ACL HttpClientsITenantDbContextFactory.csandTenantDbContextFactory.csAddJwtBearerconfiguration with dynamicIssuerSigningKeyResolver- Token generation service (
ITokenService/TokenService) signing with the tenant'sJwtSecret - Full DI registration in
Program.csincludingAddHttpMessageHandler<TenantHeaderHandler>()for all ACL HttpClients appsettings.jsonwith unifiedTenantsstructure- Unit test example mocking
ITenantResolverandTenantHeaderHandler
Unit Test Example
[Fact]
public void TenantResolver_ShouldReturn_CorrectConnectionString()
{
// Arrange
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
["Tenant:DefaultTenantId"] = "tenant-a",
["Tenants:tenant-a:ConnectionString"] = "Server=srv1;Database=TenantA_DB;",
["Tenants:tenant-a:JwtSecret"] = "test-secret-256bits-long-enough"
})
.Build();
var resolver = new TenantResolver(config);
// Act & Assert
Assert.Equal("tenant-a", resolver.TenantId);
Assert.Equal("Server=srv1;Database=TenantA_DB;", resolver.ConnectionString);
Assert.Equal("test-secret-256bits-long-enough", resolver.JwtSecret);
}
[Fact]
public async Task TenantHeaderHandler_ShouldAdd_TenantIdHeader()
{
// Arrange
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
["Tenant:DefaultTenantId"] = "tenant-b"
})
.Build();
var handler = new TenantHeaderHandler(config)
{
InnerHandler = new TestHandler()
};
var client = new HttpClient(handler);
// Act
var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost/api/test");
await client.SendAsync(request);
// Assert — verify header was added via TestHandler capture
}
private class TestHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
Assert.True(request.Headers.Contains("X-Tenant-Id"));
Assert.Equal("tenant-b", request.Headers.GetValues("X-Tenant-Id").First());
return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
}
}Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

