Getting started
This page wires Custodian into an ASP.NET Core application that uses EF Core. The code is the Shop sample.
What you need
- .NET 10 or .NET 11.
- EF Core 10 or later, or Dapper 2.1.
- SQL Server 2022 or PostgreSQL 16 or later.
1. Reference the packages
An application needs the core package for its data access, one database provider and one key store. The Shop sample references both providers because it runs on either database.
<Project Sdk="Microsoft.NET.Sdk.Web">
<ItemGroup>
<ProjectReference Include="../../src/Custodian.AspNetCore/Custodian.AspNetCore.csproj" />
<ProjectReference Include="../../src/Custodian.Dapper/Custodian.Dapper.csproj" />
<ProjectReference Include="../../src/Custodian.EntityFrameworkCore/Custodian.EntityFrameworkCore.csproj" />
<ProjectReference Include="../../src/Custodian.KeyStores.Local/Custodian.KeyStores.Local.csproj" />
<ProjectReference Include="../../src/Custodian.PostgreSql/Custodian.PostgreSql.csproj" />
<ProjectReference Include="../../src/Custodian.SqlServer/Custodian.SqlServer.csproj" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
</ItemGroup>
</Project>
The sample references the projects directly because it lives in the same repository. Your application references the packages of the same names.
Custodian.KeyStores.Local keeps keys in a directory. It is meant for development and needs no licence key.
2. Classify an entity
Mark each entity that holds personal data. The attributes say what the data is, why you hold it, on what lawful basis and for how long.
using Custodian;
namespace Shop;
/// <summary>
/// A customer account. Kept while the customer is active and deleted three years after their last activity:
/// the account exists to fulfil the contract, so it goes when the relationship does.
/// </summary>
[PersonalDataEntity(
Purpose = Purposes.CustomerAccount,
LawfulBasis = LawfulBasis.Contract,
Retention = "P3Y",
Anchor = RetentionAnchor.LastActivity,
OnExpiry = ExpiryAction.Delete)]
public sealed class Customer
{
public int Id { get; set; }
[DataSubject]
public Guid SubjectId { get; set; }
[PersonalData(DataCategory.Identity)]
public string Name { get; set; } = "";
/// <summary>Encrypted with the customer's own key, so erasure makes every copy unreadable; the blind index keeps it findable.</summary>
[PersonalData(DataCategory.Contact), Encrypted, BlindIndex]
public string Email { get; set; } = "";
[PersonalData(DataCategory.Contact)]
public string Phone { get; set; } = "";
}
[DataSubject] names the property that links the row to the person it is about. A personal entity without a purpose,
lawful basis and retention that Custodian can resolve stops the application at startup.
Classifying personal data covers every attribute.
3. Register Custodian
Custodian connects to the database with one credential per database role, never one per user. Give it a connection string for each role, a key store, and your access policy. Then tell EF Core to use it.
services.AddCustodian(o =>
{
_ = provider switch
{
"SqlServer" => o.UseSqlServer(),
"PostgreSql" => o.UsePostgreSql(),
_ => throw new InvalidOperationException($"Unknown Database:Provider '{provider}'."),
};
foreach (var role in Enum.GetValues<DbRole>())
{
o.Database.ConnectionString(
role,
configuration.GetConnectionString(role.ToString()) ?? throw new InvalidOperationException($"Set ConnectionStrings:{role}."));
}
o.KeyStore.UseLocal(keyStore);
o.Retention.FromConfiguration(configuration.GetSection("Retention"));
o.Retention.RunWorker(every: TimeSpan.FromHours(1));
ShopPolicy.Configure(o);
});
services.AddDbContext<ShopDb>((sp, db) =>
(provider == "SqlServer" ? db.UseSqlServer() : db.UseNpgsql()).UseCustodian(sp));
Keep connection strings in user secrets or environment variables, never in appsettings.json.
ShopPolicy.Configure maps the application's roles to purposes. Roles and purposes explains it.
Your DbContext also needs Custodian's own tables. Call modelBuilder.AddCustodianTables() in OnModelCreating, as
ShopDb does.
4. Add the middleware
UseCustodianContext reads the signed-in user and their tenant from the request. MapCustodianEndpoints adds the
data-subject-rights, break-glass and assisted-session endpoints.
using Custodian;
using Custodian.AspNetCore;
using Microsoft.EntityFrameworkCore;
using Shop;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddShop(builder.Configuration);
builder.Services.AddShopAuthorization();
var app = builder.Build();
app.UseAuthorization();
app.UseCustodianContext();
app.MapCustodianEndpoints(configure: ShopAuthorization.NamePolicies);
app.MapGet("/products", (ShopDb db, CancellationToken ct) =>
db.Products.AsNoTracking().ToListAsync(ct));
app.MapGet("/orders", async (ShopDb db, IProcessingContext processing, CancellationToken ct) =>
{
using var billing = processing.Begin(Purposes.Billing);
return await db.Orders.AsNoTracking().ToListAsync(ct);
});
app.Run();
public partial class Program;
The /orders endpoint shows the one thing application code must do itself. It declares why it is reading, with
processing.Begin(Purposes.Billing). The query inside is plain EF Core. ASP.NET Core covers the
middleware and the endpoints.
5. Create the schema
Create your tables as you normally do, then let Custodian install its gdpr schema and the row-level-security policies.
Run this as the role that owns the schema, not as one of the application's roles. The samples' test harness does it like this:
await using var services = CreateServices<TContext>(_ => OwnerConnectionString, custodian, services: null);
await using var scope = services.CreateAsyncScope();
await scope.ServiceProvider.GetRequiredService<TContext>().Database.EnsureCreatedAsync(cancellationToken);
await using var owner = await OpenAsOwnerAsync(cancellationToken);
await services.GetRequiredService<ICustodianSchemaInstaller>().InstallAsync(owner, cancellationToken);
Tenants and row-level security describes the database roles and what the policies do.
6. Read and write personal data
Application code opens a purpose, then uses EF Core as usual. Custodian encrypts, stamps the row with its subject and tenant, and audits on save.
public async Task<Customer?> FindByEmailAsync(string email, CancellationToken cancellationToken)
{
using var account = processing.Begin(Purposes.CustomerAccount);
var subject = await subjects.FindAsync(email, cancellationToken);
if (subject is not { } found)
{
return null;
}
return await db.Customers.SingleOrDefaultAsync(c => c.SubjectId == found.Value, cancellationToken);
}
7. See it fail closed
Without a signed-in user, a tenant and a purpose, Custodian returns no personal data. It throws
ProcessingContextMissingException.
[Theory, EachProvider]
public async Task Nobody_signed_in_cannot_read_customers(DatabaseProvider provider)
{
await using var shops = await servers.OpenShop(provider);
await shops.Nordic.SignUp(Customers.Astrid());
var reading = () => shops.WithoutContext.Query(db => db.Customers);
await Assert.ThrowsAsync<ProcessingContextMissingException>(reading);
}
The same holds below the application. A query that reaches the database without Custodian finds no rows, because
row-level security sees no session context. The test
Raw_sql_without_session_context_finds_no_customers proves it on both databases.
Run the samples
Docker must be running. The acceptance tests start their own SQL Server and PostgreSQL containers.
build/test.sh --integration
The tests are written to be read. The Shop walkthrough lists them in a sensible order.