Table of Contents

Users see only their own data

A notes application: each user has notebooks with notes, and sees, edits, and deletes only their own. The client never says whose a notebook is, and can’t reach the notebooks of others even by their identifiers. The code is in docs/samples/Recipes.

The idea:

  1. the entity stores its owner;
  2. query prefilters restrict every query to the current user;
  3. a custom service sets the owner of the new and the edited objects;
  4. a model validator checks that the objects a new one refers to are the user’s too.

The owner

The notebook stores the identifier of its user. The model has it too, so the service can set it, but the DTO and the filter don’t: the clients neither see nor send it, and can’t filter by it.

using Magicalizer.Data.Entities.Abstractions;

namespace App.Data.Entities;

public class Notebook : IEntity<int>
{
  public int Id { get; set; }
  public string UserId { get; set; } = null!;
  public string? Name { get; set; }
  public virtual ICollection<Note>? Notes { get; set; }
}
using Magicalizer.Filters.Abstractions;

namespace App.Filters;

// There is no UserId: the prefilter decides whose notebooks are seen, not the client.
public class NotebookFilter : IFilter
{
  public IntegerFilter? Id { get; set; }
  public StringFilter? Name { get; set; }
  public EnumerableFilter<NoteFilter>? Notes { get; set; }
}

A note doesn’t store its owner: it belongs to the user of its notebook.

The current user

The domain layer doesn’t depend on HTTP, so it gets the user through an interface of its own:

namespace App.Domain;

// The user the code works for. The domain doesn't depend on HTTP, so it gets the user through this interface.
public interface ICurrentUser
{
  string? Id { get; }
}

The web application implements it with the user of the request:

using System.Security.Claims;
using App.Domain;

namespace App.Infrastructure;

public class HttpCurrentUser : ICurrentUser
{
  private readonly IHttpContextAccessor httpContextAccessor;

  public HttpCurrentUser(IHttpContextAccessor httpContextAccessor)
  {
    this.httpContextAccessor = httpContextAccessor;
  }

  // A real scheme usually puts the identifier into the NameIdentifier claim, the sample one uses the name.
  public string? Id => this.httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.Name);
}

A background job or a test registers its own implementation (e.g. a fixed user, or none).

The prefilters

One prefilter for each entity the clients reach directly:

using App.Domain;
using App.Filters;
using Magicalizer.Domain.Services.Abstractions;

namespace App.Data.Prefilters;

public class OwnNotebookPrefilter : IQueryPrefilter<Entities.Notebook, NotebookFilter>
{
  private readonly ICurrentUser currentUser;

  public OwnNotebookPrefilter(ICurrentUser currentUser)
  {
    this.currentUser = currentUser;
  }

  public IQueryable<Entities.Notebook> Apply(IQueryable<Entities.Notebook> query, NotebookFilter? filter)
  {
    string? userId = this.currentUser.Id;

    // Without a user, there is nothing to see.
    if (userId == null)
      return query.Where(n => false);

    return query.Where(n => n.UserId == userId);
  }
}
using App.Domain;
using App.Filters;
using Magicalizer.Domain.Services.Abstractions;

namespace App.Data.Prefilters;

public class OwnNotePrefilter : IQueryPrefilter<Entities.Note, NoteFilter>
{
  private readonly ICurrentUser currentUser;

  public OwnNotePrefilter(ICurrentUser currentUser)
  {
    this.currentUser = currentUser;
  }

  public IQueryable<Entities.Note> Apply(IQueryable<Entities.Note> query, NoteFilter? filter)
  {
    string? userId = this.currentUser.Id;

    if (userId == null)
      return query.Where(n => false);

    // A note belongs to the user of its notebook.
    return query.Where(n => n.Notebook!.UserId == userId);
  }
}
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICurrentUser, HttpCurrentUser>();
builder.Services.AddScoped<IQueryPrefilter<Notebook, NotebookFilter>, OwnNotebookPrefilter>();
builder.Services.AddScoped<IQueryPrefilter<Note, NoteFilter>, OwnNotePrefilter>();

Now a notebook of another user behaves as if it doesn’t exist: it isn’t in the lists, and getting, replacing, patching, or deleting it is 404 Not Found. The DTOs are marked with [AuthenticatedOnly], so an anonymous request is 401 Unauthorized before it reaches the prefilters.

Setting the owner

The prefilters restrict the existing objects, but a new one gets its owner from the service:

using App.Domain.Models;
using App.Filters;
using FluentValidation;
using Magicalizer.Domain.Services;
using Magicalizer.Domain.Services.Abstractions;
using Microsoft.EntityFrameworkCore;

namespace App.Domain.Services;

public class NotebookService : Service<int, Data.Entities.Notebook, Notebook, NotebookFilter>
{
  private readonly ICurrentUser currentUser;

  public NotebookService(ICurrentUser currentUser, DbContext dbContext, IEnumerable<IQueryPrefilter<Data.Entities.Notebook, NotebookFilter>>? queryPrefilters = null, IValidator<Notebook>? validator = null) : base(dbContext, queryPrefilters, validator)
  {
    this.currentUser = currentUser;
  }

  public override Task<Notebook> CreateAsync(Notebook model, CancellationToken cancellationToken = default)
  {
    // A new notebook belongs to the current user, whatever the client sends.
    model.UserId = this.GetUserId();
    return base.CreateAsync(model, cancellationToken);
  }

  public override Task EditAsync(Notebook model, CancellationToken cancellationToken = default)
  {
    // The DTO has no user, so it's kept (the prefilter lets the user edit only the own notebooks).
    model.UserId = this.GetUserId();
    return base.EditAsync(model, cancellationToken);
  }

  private string GetUserId()
  {
    return this.currentUser.Id ?? throw new InvalidOperationException("There is no current user.");
  }
}

EditAsync sets the owner too: the DTO has no owner, so the model that comes from PUT or PATCH has none, and the entity would lose it. Setting it to the current user is safe, as the prefilter has already checked that the notebook is the user’s (otherwise it’s 404 Not Found).

The references

A note refers to a notebook, and the client sends its identifier. Without a check, a user could put a note into the notebook of another user. The model validator checks it through the notebook service, which is prefiltered too:

using App.Filters;
using FluentValidation;
using Magicalizer.Domain.Services.Abstractions;

namespace App.Domain.Models.Validators;

public class NoteValidator : AbstractValidator<Note>
{
  public NoteValidator(IService<int, Notebook, NotebookFilter> notebookService)
  {
    // The notebook service is prefiltered, so a notebook of another user isn't found either.
    this.RuleFor(n => n.Notebook!.Id)
      .MustAsync(async (id, cancellationToken) => await notebookService.GetByIdAsync(id, cancellationToken: cancellationToken) != null)
      .WithMessage("The notebook doesn't exist.")
      .When(n => n.Notebook != null);
  }
}
POST /v1/notes
X-User: bob
Content-Type: application/json

{"notebook": {"id": 1}, "title": "Spam"}
{
  "status": 400,
  "errors": {
    "Notebook.Id": ["The notebook doesn't exist."]
  }
}

The validator runs in the service, for the creation and the editing alike, so a note can’t be moved to a foreign notebook either.

Warning

A prefilter restricts the queries of its own entity: the lists, the counts, and the objects by the primary key. It doesn’t restrict the related objects of another entity: the included ones and the conditions of the related objects.

Here it’s enough: each entity the clients reach is prefiltered, and everything related to an own notebook or note is the user’s too. It isn’t enough when a shared entity refers to the private ones, e.g. a public Tag with the notes of all the users: GET /v1/tags?include=notes would return the notes of everyone. Then:

  • don’t give the shared entity the navigation property to the private ones (or don’t allow including it); or
  • restrict the private entity in EF Core itself, with a global query filter, which applies to every query, including the inclusions:
public class AppDbContext : DbContext
{
  private readonly ICurrentUser currentUser;

  public AppDbContext(DbContextOptions<AppDbContext> options, ICurrentUser currentUser) : base(options)
  {
    this.currentUser = currentUser;
  }

  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Note>(etb => {
      // The filter reads the user of this context instance, so each request gets its own.
      etb.HasQueryFilter("Owner", e => e.Notebook!.UserId == this.currentUser.Id);
    });
  }
}

The soft deletion recipe uses a global query filter the same way.

Several tenants

A multi-tenant application is the same recipe one level up: the entities store the tenant instead of (or besides) the user, ICurrentUser becomes ICurrentTenant (from a claim, a header, or the host name), and the prefilters or the global query filters compare the tenant. When most entities belong to a tenant, the global query filters are usually simpler, as one convention in the DbContext covers all of them, the related objects included.

Tests

The Recipes.Tests project checks the recipe through HTTP (see Testing):

[Fact]
public async Task User_sees_only_own_notebooks()
{
  CancellationToken cancellationToken = TestContext.Current.CancellationToken;
  HttpClient alice = this.factory.CreateClient("alice");
  HttpClient bob = this.factory.CreateClient("bob");

  HttpResponseMessage created = await alice.PostAsJsonAsync("/v1/notebooks", new Notebook { Name = "Alice's" }, cancellationToken);
  Notebook? notebook = await created.Content.ReadFromJsonAsync<Notebook>(cancellationToken);

  Assert.Equal(HttpStatusCode.Created, created.StatusCode);

  Notebook[]? bobsNotebooks = await bob.GetFromJsonAsync<Notebook[]>("/v1/notebooks", cancellationToken);
  HttpResponseMessage bobsResponse = await bob.GetAsync($"/v1/notebooks/{notebook!.Id}", cancellationToken);

  Assert.DoesNotContain(bobsNotebooks!, n => n.Id == notebook.Id);
  Assert.Equal(HttpStatusCode.NotFound, bobsResponse.StatusCode);
}

See also