Skip to the content.

Security and multi-tenancy

Isolation and permissions are enforced by the engine on every read and write, not left to each page.

Permissions

With AddHttpApi(), permissions come from the signed-in user’s claims (type permission, configurable with PermissionClaimType). Deny by default: anonymous callers get 401, callers without the claim 403.

Claim Grants
crud:cities:view List, get, schema, lookups of cities
crud:cities:create / update / delete That action
crud:cities:restore See and restore soft-deleted rows
crud:cities:purge Delete soft-deleted rows for good: only this exact claim, never a wildcard
crud:cities:* Every action of cities except purge
crud:* Every action of every page except purge
crud:cities:{name}:view / :edit A [Restricted] field: only this exact claim (below)
crud:cities:all Skip the page’s row rules: only this exact claim (below)

CrudPages.City.Claims.View etc. hold these strings. The schema’s permissions tells UIs which buttons to show.

The host role (AddHttpApi(o => o.HostRole = "admin")) may do everything, including purge, across tenants.

Roles in the database (Attritect.Permissions)

Keep roles in your own database and manage them from screens instead of issuing claims:

// DbContext.OnModelCreating
modelBuilder.AddCrudPermissions();             // CrudRoles, CrudRolePermissions, CrudUserRoles (add a migration)

// Program.cs
builder.Services.AddCrudEngine(o => o.AddPagesFrom(...).AddPermissionPages())   // Roles, Role permissions, User roles
    .UseEntityFrameworkCore<AppDbContext>()
    .AddHttpApi(o => o.HostRole = "admin")
    .UseDatabasePermissions<AppDbContext>();   // database roles + permission claims

Your own rules: implement ICrudPermissionProvider and register it; the engine never replaces your registration. Implement its second IsAllowedAsync(permission, right) for restricted fields and “all rows”: the default answer is no (fail closed). AllowAllPermissions = true switches checks off (development only).

Pages the API only reads

[CrudPage("audit-notes", Entity = typeof(AuditNote), ApiReadOnly = true)]   // a page you own
o.MakeApiReadOnly("some-page");                                             // a page you don't
o.AddPermissionPages(apiReadOnly: true);                                    // the three role pages

Create, update, delete, restore and purge over HTTP (and the Pro import) answer 403 for everyone, the host role included; the schema reports them as not allowed, so UIs hide the buttons. Your own code (services, seed data, jobs) still writes the page. Lock the role pages when the host must not reach tenant data: otherwise the host, who is allowed everything, could assign itself a role in any tenant through the API.

What the host role can do

The host is allowed every permission, across tenants: it reads every tenant’s rows, writes shared pages (the role pages too), sees restricted fields and, with Pro, every tenant’s audit history. If your platform admins must not see or change tenant data, don’t give them the host role for that work, lock the role pages, and narrow the rest by replacing the permission provider.

Code that calls the service

The HTTP API checks permissions before it calls ICrudService<T>; the service itself doesn’t, by default, so a job or use case that calls it on behalf of a user must check first:

if (!await permissions.IsAllowedAsync("orders", CrudAction.Update, ct))   // ICrudPermissionProvider
    throw new CrudForbiddenException("You may not change orders.");
await orders.UpdateAsync(id, model, ct);

Or turn on o.EnforcePermissionsInService = true in AddCrudEngine: the service then checks list, get, create, update, delete, restore, purge and lookups itself. Code that runs without a user (seeding, background jobs) then needs a permission provider that allows it. Your own EF queries are never checked or tenant-filtered by the engine: filter and check them yourself.

Permissions stay current

The database permission provider keeps a caller’s grants until the role pages change (saves through them signal it) or MaxCacheAge passes (default 1 minute), so a Blazor circuit open for hours sees new and removed roles. When your own code writes the role tables, call CrudPermissionChanges.Notify().

Options belong to the classes that read them

AddHttpApi(o => ...) options are read by the default HTTP classes: HostRole and PermissionClaimType by ClaimsPermissionProvider and HttpTenantContext, TenantClaimType and TenantHeader by HttpTenantContext. Replace one of those classes and its options no longer apply: your replacement decides (the database permission provider, for example, takes the host from the tenant context).

Restricted fields

[Grid, Field, Restricted("salary")]
public decimal? Salary { get; set; }
Claim Effect
none The value is removed (null), the column and field leave the schema, filtering or sorting on it is a 400
crud:employees:salary:view Visible; in forms it’s read-only and saving keeps the stored value
...:salary:view + ...:salary:edit Normal field

Only the exact claims or the host role grant these; crud:* doesn’t. Use a nullable type so hidden values read as null. Exports leave hidden columns out, imports can’t set read-only fields, and audit history hides their values. The generator adds CrudPages.Employee.Claims.Salary.View / .Edit.

Row rules

Limit which rows a caller sees and changes, inside their tenant:

[CrudPage("work-items", Entity = typeof(WorkItem))]
[OwnRows]                                            // only rows they created (the entity's CreatedBy)
public class WorkItemModel { ... }

[CrudPage("orders", Entity = typeof(Order))]
[ScopeBy(nameof(Order.BranchId), "branch_id")]       // BranchId must be one of the user's branch_id claims
public class OrderModel { ... }

public class ConfidentialRule(ICrudUser user) : ICrudRowRule<Document>   // anything else, as a filter
{
    public ValueTask<Expression<Func<Document, bool>>?> GetFilterAsync(string page, CancellationToken ct) =>
        ValueTask.FromResult<Expression<Func<Document, bool>>?>(user.Id == "boss" ? null : d => !d.Confidential);
}

Multi-tenancy

builder.Services.AddCrudEngine(o => o.AddPagesFrom(asm).UseMultiTenancy<int>())   // tenant key type

Who is the tenant: the user’s tenant_id claims (TenantClaimType) list their tenants; with several, the X-Tenant header (TenantHeader) picks the active one. A tenant the user doesn’t belong to is a 403. Override HttpTenantContext (or register your own ITenantContext) for other schemes.

Which pages are tenant data ([CrudPage(Tenancy = ...)]):

Tenancy Rows Who writes
Auto (default) Tenant-owned if the entity has TenantId, else global  
Tenant Each tenant sees only its rows the tenant
Shared Everyone reads the same rows the host only
SharedWithTenantRows Shared rows (TenantId = null) plus each tenant’s own host: shared rows; tenants: their own

What the engine guarantees: lists, gets, lookups, unique checks and reference checks are filtered; new rows get the active tenant (never a value from the request); another tenant’s row is a 404 (its existence isn’t revealed); updates can’t move a row to another tenant.

Tenant databases

Any tenant can have its own database while the others share one; global pages use a host database:

engine.UseTenantDatabases<AppDbContext>((o, cs) => o.UseSqlServer(cs), t =>
{
    t.Host = hostConnection;
    t.Shared = sharedConnection;
    t.Dedicated(42, tenant42Connection);     // tenant 42 alone
});

Or t.UseResolver<MyResolver>() (an ITenantConnectionResolver) to read the mapping from anywhere. The tenant filter stays on in every database.

Read replicas

engine.UseReadStore<ReplicaDbContext>();     // same model, another connection

Lists, gets and lookups read the replica; everything that must be current (reloading a row just saved, unique and foreign-key checks, loading rows to change) uses the write side.

Other protections