Skip to content

5. Authorize catalog access with Cratis Arc

Restrict the library catalog to authenticated callers with the Librarian role. Cratis Arc checks role declarations on commands and queries before running them, so you can protect catalog reads and writes without adding permission checks inside each handler. This chapter finishes the tutorial by testing server enforcement, including calls that bypass the React buttons.

Continue with the standalone host from chapter 1; for TypeScript use the standalone MongoDB host, retaining its tenant resolver when adding the development header handler. Add global using Cratis.Arc.Authorization; to GlobalUsings.cs on C#; on the JVM, import io.cratis.arc.authorization.Roles in the files that use it. The TypeScript snippets import roles from @cratis/arc.core. This chapter uses the role name Librarian; it must match an authorization role on the authenticated principal. No identity-details provider is required.

On C#, the first excerpt below also declares a one-member LibraryRole enum; put it in its own file, src/LibraryRole.cs, under namespace Library; so every feature folder can use it. The C# excerpts pass nameof(LibraryRole.Librarian), which is still the string "Librarian". Arc’s ARC0011 analyzer warns about string literals in [Roles]; with nameof, a mistyped role name is a compile error instead of a silent denial. The JVM and TypeScript snippets pass the same name as a string.

Add [Roles(...)] on C#, @Roles(...) on the JVM, or @roles(...) on TypeScript to require a role before the command runs. The excerpts show the document-store branch. If you chose relational storage, keep the handler you already have and add only the role declaration. On the JVM, replace @AllowAnonymous with @Roles("Librarian"); do not keep both on the same declaration.

Start with RegisterAuthor. The TypeScript prerequisite host also exposes RenameAuthor, so its tab protects that command too:

public enum LibraryRole
{
Librarian
}
[Command]
[Roles(nameof(LibraryRole.Librarian))]
public record RegisterAuthor(AuthorId Id, AuthorName Name)
{
public Task Handle(IMongoCollection<Author> authors) =>
authors.InsertOneAsync(new Author(Id, Name));
}

View C# snippet source on GitHub

Apply the same role to AddBook. On the JVM, replace its @AllowAnonymous annotation. The .NET and JVM chapter-1 projects do not include RenameAuthor; if you added it from the standalone-slice example, protect it too. Keep each handler’s database write unchanged.

Protecting writes does not restrict who can read the catalog. Add the role declaration to both AllAuthors and BooksForAuthor to require Librarian for these queries too. On the JVM, remove the chapter-1 @AllowAnonymous class annotation from Author and the chapter-3 one from Book, then add @Roles("Librarian") to each query operation. Leaving an anonymous class default would allow other queries on that read model to remain public when they have no declaration of their own:

[ReadModel]
public record Author(AuthorId Id, AuthorName Name)
{
[Roles(nameof(LibraryRole.Librarian))]
public static ISubject<IEnumerable<Author>> AllAuthors(IMongoCollection<Author> authors) =>
authors.Observe();
}

View C# snippet source on GitHub

For queries, a method’s own authorization declaration takes precedence over the read-model class default. On the JVM, @AllowAnonymous, @Authorize, or @Roles on an operation replaces the class declaration entirely; roles are not merged with the class’s roles. See authorization on artifacts and operations before mixing public and protected queries on one read model.

On C#, Arc checks ClaimsPrincipal.IsInRole("Librarian"), so configure your authentication scheme’s role claims accordingly. An application detail such as LibraryIdentity.Role does not grant the role. IProvideIdentityDetails enriches client/domain context; its rejected result controls /.cratis/me, not every operation.

The JVM asks the same question of an ArcPrincipal: a caller holds Librarian when one of its roles is that name, which is what a Spring Security ROLE_Librarian authority becomes once Arc drops the prefix. On TypeScript, the microsoftIdentityPlatform() development handler reads Librarian from the header principal’s userRoles. An IdentityDetailsProvider plays the same enriching, non-granting role there as IProvideIdentityDetails does here.

For the local checkpoint, the .NET and TypeScript examples accept a principal from development headers. These adapters do not validate bearer-token signatures, issuer, or audience: they trust the headers. Keep the host bound to loopback and never expose this header-spoofing fixture publicly. Production needs a properly configured authentication scheme or an authenticated trusted ingress that replaces spoofable headers and prevents direct backend access.

Select the adapter for your backend before building the host. The TypeScript builder registers its header handler alongside the MongoDB host’s tenant resolver. The JVM bridge requires a verified trusted ingress, so JVM readers should follow the security guide below rather than treating it as a local property toggle:

if (builder.Environment.IsDevelopment())
{
builder.Services.AddMicrosoftIdentityPlatformIdentityAuthentication();
builder.Services.Configure<ArcOptions>(options => options.TrustForwardedIdentityHeaders = true);
}

View C# snippet source on GitHub

On .NET, before app.UseCratisArc(), add the authentication middleware. The TypeScript builder’s authentication option already covers this step:

if (app.Environment.IsDevelopment())
{
app.UseAuthentication();
}

View C# snippet source on GitHub

Keep the host bound to loopback for this development checkpoint: http://localhost:5000 on C#, or http://127.0.0.1:3000 on TypeScript. Spring Boot listens on all interfaces by default; JVM readers must set server.address=127.0.0.1 in local configuration before using http://127.0.0.1:8080. A port number alone does not restrict who can reach the server. Follow Generate a local principal on C# or Simulate a signed-in user locally on TypeScript to send the three x-ms-client-principal headers through the local Vite proxy. In the principal JSON, include "Librarian" in userRoles, then Base64-encode it locally. Restrict the browser header override to your localhost app URLs. On the JVM, use an authenticated ArcPrincipal carrying that role through your own handler or verified ingress (see below).

Verify permissions, not just UI visibility

Section titled “Verify permissions, not just UI visibility”

Rebuild and restart the C# checkpoint with -e ASPNETCORE_ENVIRONMENT=Development, or start the TypeScript host with NODE_ENV=development on port 3000. In these examples the header adapters are registered only in development; a Production host without another authentication scheme rejects even the Librarian header case. On the JVM, start the host with your authentication handler configured.

Test each case separately, using the local headers on .NET and TypeScript or the credentials your JVM handler accepts:

  1. Without identity headers, protected commands and queries must reject access.
  2. With a valid local principal but no Librarian role, they must still reject access.
  3. With an authenticated principal carrying Librarian (userRoles in the header fixture), list authors and register one successfully.
  4. Remove the role again. Hiding a button is optional UI behavior; a direct operation call must still fail.

Inspect isAuthorized on the command/query result. Authentication middleware may reject a request before an Arc result is created, so also inspect the HTTP response. Repeat the checks for AddBook and BooksForAuthor, and for RenameAuthor if your host exposes it. Check direct operation calls as well as the UI so an unprotected endpoint cannot be hidden by a missing button.

For production authentication and domain details, continue with Identity and Authorizing commands and queries, the JVM security guide, or TypeScript’s authentication guide.

The library app now has author registration and a book catalog connected to React through generated proxies. Validators report blank or duplicate names, a database constraint enforces name uniqueness, and observable queries supply catalog updates within the scope you checked in chapter 4. Role declarations restrict the catalog operations to an authenticated librarian.

The app uses CQRS, the separation of writes from reads, over a database without an event store. Commands write current state; queries return the read models the screens need. Keep that structure for another feature, and regenerate proxies when its backend contracts change.

You already used Components for command forms and dialogs; explore its other UI components when building the next screen. If you need recorded business history rather than only current state, consider Cratis Chronicle as a separate event-sourcing integration. The Cratis Stack tour explains how these products fit together without making them prerequisites for this app.