How to Implement Multi-Tenant RAG in ASP.NET Core 10 Using C# and PostgreSQL (2026)

Two customers can upload nearly identical policies while still requiring strict separation. Similarity search will happily rank both results together unless tenant isolation is enforced before any passage reaches the answer model.

This tutorial builds tenant-aware vector retrieval in ASP.NET Core 10. It derives a workspace from verified JWT claims, passes tenant context into a PostgreSQL transaction, and enforces a read policy with row-level security. Two rows with identical vectors make accidental leakage easy to detect.

Where should tenant isolation happen?

The API derives a workspace from a verified token. PostgreSQL row-level security filters the authorized rows before any passages leave the database.
The API derives a workspace from a verified token. PostgreSQL row-level security filters the authorized rows before any passages leave the database.

Authorize the tenant at the API boundary and restrict rows in the database. A client-supplied tenant field is a routing hint at most. The example accepts no tenant field in the request. It expects one trusted workspace_id claim and the rag.read scope. Configure your issuer to mint that claim only for an authorized workspace. If the issuer does not own tenant membership, resolve it in your application before opening the database transaction.

Boundary Enforcement Failure prevented
JWT middleware Valid issuer, audience and token lifetime Using a token issued for another API
Application policy Required scope and trusted workspace Choosing a tenant through request JSON
SQL query Explicit tenant predicate Accidental unfiltered query plan or retrieval
PostgreSQL RLS Policy on the reader role A missing tenant predicate in another query

RLS is a backstop against query mistakes. This configuration trusts the application to set the correct transaction context. A compromised app that can execute arbitrary SQL as the reader can set a different context. Use parameterized queries, secure credentials and isolate database roles. Consider separate databases where the threat model requires stronger isolation.

Create the PostgreSQL policy and server

Install .NET 10, PostgreSQL with pgvector, psql, and a JWT issuer that can provide two distinct workspace claims. Use a disposable database. Run schema.sql as the database administrator, then use psql’s password prompt for the reader role. Configure the app with that role, never the table owner or a superuser. For pooled connections, use transaction-local set_config and explicitly start a transaction for every protected lookup.

schema.sql
-- Run as a PostgreSQL administrator in a disposable database.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE ROLE rag_reader LOGIN NOBYPASSRLS;
-- Set the role password separately in psql using \password rag_reader.
CREATE TABLE tenant_chunks (
    tenant_id uuid NOT NULL,
    chunk_id bigint GENERATED ALWAYS AS IDENTITY,
    content text NOT NULL,
    embedding vector(3) NOT NULL,
    PRIMARY KEY (tenant_id, chunk_id)
);
INSERT INTO tenant_chunks (tenant_id, content, embedding) VALUES
('11111111-1111-1111-1111-111111111111', 'Tenant A refunds', '[1,0,0]'),
('22222222-2222-2222-2222-222222222222', 'Tenant B restricted', '[1,0,0]');
ALTER TABLE tenant_chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE tenant_chunks FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_read ON tenant_chunks FOR SELECT TO rag_reader
USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);
GRANT USAGE ON SCHEMA public TO rag_reader;
GRANT SELECT ON tenant_chunks TO rag_reader;

The policy uses NULLIF because an unset or reset custom setting may be missing or empty. With no tenant it grants no rows. FORCE ROW LEVEL SECURITY subjects the table owner to policy in ordinary use. It does not make a superuser or role with BYPASSRLS safe. The reader role has no write grants and receives select access only to the intended table. See PostgreSQL row security policies.

Lab.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
  <ItemGroup><PackageReference Include="Npgsql" Version="10.0.3" /></ItemGroup>
  <ItemGroup><PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.11" /></ItemGroup>
</Project>
Program.cs
using System.Globalization;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Npgsql;

var builder = WebApplication.CreateBuilder(args);
var authority = builder.Configuration["Auth:Authority"];
var audience = builder.Configuration["Auth:Audience"];
if (!Uri.TryCreate(authority, UriKind.Absolute, out var issuer) ||
    issuer.Scheme != "https" || string.IsNullOrWhiteSpace(audience))
    throw new InvalidOperationException("Set an HTTPS Auth__Authority and Auth__Audience.");
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o => { o.Authority = authority; o.Audience = audience; o.MapInboundClaims = false; });
builder.Services.AddAuthorizationBuilder().AddPolicy("rag.read", p =>
    p.RequireAuthenticatedUser().RequireAssertion(c =>
        c.User.FindAll("scp").Concat(c.User.FindAll("scope")).Any(x =>
            x.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries).Contains("rag.read"))));
builder.Services.AddSingleton(_ => NpgsqlDataSource.Create(
    builder.Configuration.GetConnectionString("Db") ?? throw new InvalidOperationException("Set ConnectionStrings__Db.")));
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapPost("/search", async (Query body, HttpContext ctx, NpgsqlDataSource db, CancellationToken ct) =>
{
    var tenants = ctx.User.FindAll("workspace_id").Select(x => x.Value).ToArray();
    if (tenants.Length != 1 || !Guid.TryParse(tenants[0], out var tenant) || tenant == Guid.Empty)
        return Results.Forbid();

    if (body.Vector is not { Length: 3 } || !body.Vector.All(float.IsFinite) ||
        body.Vector.All(v => v == 0))
        return Results.BadRequest("Expected a nonzero finite three-element vector.");
    var vector = "[" + string.Join(",", body.Vector.Select(v =>
        v.ToString("R", CultureInfo.InvariantCulture))) + "]";

    await using var conn = await db.OpenConnectionAsync(ct);
    await using var tx = await conn.BeginTransactionAsync(ct);
    await using (var set = new NpgsqlCommand("SELECT set_config('app.tenant_id', @tenant, true)", conn, tx))
    {
        set.Parameters.AddWithValue("tenant", tenant.ToString());
        await set.ExecuteNonQueryAsync(ct);
    }

    var hits = new List<Hit>();
    await using (var cmd = new NpgsqlCommand("""
        SELECT chunk_id, content FROM tenant_chunks WHERE tenant_id = @tenant
        ORDER BY embedding <=> CAST(@embedding AS vector), chunk_id LIMIT 5
        """, conn, tx))
    {
        cmd.Parameters.AddWithValue("tenant", tenant);
        cmd.Parameters.AddWithValue("embedding", vector);
        await using var reader = await cmd.ExecuteReaderAsync(ct);
        while (await reader.ReadAsync(ct))
            hits.Add(new(reader.GetInt64(0), reader.GetString(1)));
    }

    await tx.CommitAsync(ct);
    return Results.Ok(hits);
}).RequireAuthorization("rag.read");

await app.RunAsync();

record Query(float[] Vector);
record Hit(long Id, string Text);
Configure and run the retrieval API
psql "$ADMIN_DATABASE_URL" -v ON_ERROR_STOP=1 -f schema.sql
# In psql as admin, use: \password rag_reader
export Auth__Authority='https://your-token-issuer.example'
export Auth__Audience='your-rag-api'
# Set ConnectionStrings__Db to an Npgsql connection string for rag_reader.
dotnet run --no-launch-profile -- --urls http://127.0.0.1:5080

The PostgreSQL connection string and access tokens should come from controlled configuration, and the deployed endpoint and database connection should use TLS appropriate to the environment. The local fixture uses a three-element vector. When integrating a real embedding provider, validate model and dimensionality together. See the ASP.NET PB RAG chatbot tutorial for the rest of the ingestion and generation path.

Verify cross-tenant denial

As rag_reader, run the following against the disposable database. It deliberately omits the explicit application predicate to test the database policy itself.

Exercise RLS independently of the API
SELECT content FROM tenant_chunks; -- expect zero rows
BEGIN;
SELECT set_config('app.tenant_id','11111111-1111-1111-1111-111111111111',true);
SELECT content FROM tenant_chunks; -- expect only Tenant A refunds
COMMIT;
SELECT content FROM tenant_chunks; -- expect zero rows again

For the API, use two valid access tokens with rag.read and the fixture workspace IDs. Post the same vector with both tokens. Assert that each result contains only its expected row. Include an unauthorized token, a missing scope, and a malformed or duplicated workspace claim. Verify repeated A/B requests over pooled connections. Validate the error path too by forcing a failure within a transaction and then making an authorized request from another tenant.

Search with a token for workspace A
curl -i http://127.0.0.1:5080/search \
  -H "Authorization: Bearer $TENANT_A_ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"vector":[1,0,0]}'

Expected content for A is Tenant A refunds. Expected content for B is Tenant B restricted. The identical vectors demonstrate that isolation comes from the authenticated workspace and RLS, not from vector distance.

The C# project compiled with .NET SDK 10.0.100. PostgreSQL-backed runtime verification was not performed here.

Carry tenant context through the rest of RAG

Apply the same rule to ingestion, source lookup, status queries, durable jobs, evaluation logs, caches and deletion. Cache keys need the tenant and all authorization-relevant scope. A globally shared answer cache can leak passages even if the vector query was correctly scoped. When the authorization model is document-level, attach document permissions to each candidate and check them before retrieving text. A tenant-level claim alone is insufficient.

For an ANN index, inspect the interaction between the tenant filter and candidate selection. Compare recall against exact search using a representative distribution of large and small tenants. Consider partitioning or targeted partial indexes where operationally justified. Avoid benchmarking only one large tenant and extrapolating to every customer. See pgvector filtering and PostgreSQL configuration functions.

Symptom What to check
Every query returns zero Role, policy, transaction context and UUID
Rows are visible without tenant context Connection role is owner, superuser or BYPASSRLS
Tenant appears to leak after a request Session-level context or a cache missing tenant scope
Fewer hits with ANN Filter selectivity and approximate search behavior
Valid token gets 403 Issuer claim mapping, scope, or invalid workspace ID

FAQ and references

Can I filter tenant IDs after vector search in C#? Filter before returning candidates from the database. Post-filtering may leak through logs or intermediates and loses useful tenant-specific candidates.

Why use transaction-local settings? The setting is scoped to the active transaction, which makes it easier to reason about pooled connections and rollback.

Is RLS enough for shared caches or prompt assembly? Each subsystem needs its own tenant and authorization checks. RLS only governs the rows the database returns.

Test two tenants with intentionally indistinguishable vectors and distinct private text. That fixture catches mistakes that a single-tenant test will miss.

Comments