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.
Prerequisites
Section titled “Prerequisites”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.
Gate the commands
Section titled “Gate the commands”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));}@Command@Roles("Librarian")public record RegisterAuthor(AuthorId id, AuthorName name) { public void handle(@FromServices AuthorRepository authors) { authors.save(new Author(id, name)); }}@Command@Roles("Librarian")data class RegisterAuthor(val id: AuthorId, val name: AuthorName) { suspend fun handle(@FromServices authors: AuthorRepository) { authors.save(Author(id, name)) }}import { field } from '@cratis/fundamentals';import { command, commandReadModel, inject, key, roles } from '@cratis/arc.core';
@command()@roles('Librarian')export class RegisterAuthor { @field(AuthorId) id!: AuthorId; @field(AuthorName) name!: AuthorName;
@inject(AuthorRepository) handle(authors: AuthorRepository): Promise<void> { return authors.save({ id: this.id, name: this.name }); }}
@command()@roles('Librarian')export class RenameAuthor { @field(AuthorId) @key() id!: AuthorId; @field(AuthorName) newName!: AuthorName;
@inject(commandReadModel(Author), AuthorRepository) async handle(author: Author, authors: AuthorRepository): Promise<void> { author.name = this.newName; await authors.save(author); }}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.
Gate the queries
Section titled “Gate the queries”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();}@ReadModelpublic record Author(AuthorId id, AuthorName name) { @Roles("Librarian") public static Flow.Publisher<List<Author>> allAuthors(@FromServices MongoObservableQuery queries) { return queries.observePublisher(Author.class); }}@ReadModeldata class Author(val id: AuthorId, val name: AuthorName) { companion object { @JvmStatic @Roles("Librarian") fun allAuthors(@FromServices queries: MongoObservableQuery): Flow<List<Author>> = queries.observe<Author>() }}import { field } from '@cratis/fundamentals';import { query, readModel, roles, service, type ObservableSource } from '@cratis/arc.core';
@readModel()export class Author { @field(AuthorId) id!: AuthorId; @field(AuthorName) name!: AuthorName;
@roles('Librarian') @query({ observable: true }, service(AuthorRepository)) static allAuthors(authors: AuthorRepository): ObservableSource<Author[]> { return authors.observeAll(); }}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.
Where the roles come from
Section titled “Where the roles come from”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);}Java does not support this workflow yet: the ASP.NET Core adapter is .NET-only. On the JVM, Arc.Kotlin's optional platform identity bridge reads the same x-ms-client-principal headers, but requires cratis.arc.platform-identity.enabled=true and an ArcPlatformIdentityTrust bean that verifies your ingress strips caller-supplied headers. There is no safe generic trust bean to copy: see /arc/backend/kotlin/guides/security/. For another local identity mechanism, register io.cratis.arc.authentication.AsyncAuthenticationHandler.Kotlin does not support this workflow yet: the ASP.NET Core adapter is .NET-only. On the JVM, Arc.Kotlin's optional platform identity bridge reads the same x-ms-client-principal headers, but requires cratis.arc.platform-identity.enabled=true and an ArcPlatformIdentityTrust bean that verifies your ingress strips caller-supplied headers. There is no safe generic trust bean to copy: see /arc/backend/kotlin/guides/security/. For another local identity mechanism, register io.cratis.arc.authentication.AuthenticationHandler.import { ArcApplication, microsoftIdentityPlatform } from '@cratis/arc.core';
const development = process.env.NODE_ENV === 'development';const builder = ArcApplication.createBuilder({ tenancy: { resolve: () => 'default' }, development, authentication: development ? [microsoftIdentityPlatform()] : []});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();}Java does not support this workflow yet: ASP.NET Core's UseAuthentication is .NET-only. Spring Boot's security chain and Arc.Kotlin's io.cratis.arc.authentication.AsyncAuthenticationHandler beans handle authentication on the JVM; see /arc/backend/kotlin/guides/security/ for the platform filter-chain and handler setup.Kotlin does not support this workflow yet: ASP.NET Core's UseAuthentication is .NET-only. Spring Boot's security chain and Arc.Kotlin's io.cratis.arc.authentication.AuthenticationHandler beans handle authentication on the JVM; see /arc/backend/kotlin/guides/security/ for the platform filter-chain and handler setup.TypeScript does not support this workflow yet: ASP.NET Core's separate UseAuthentication middleware step is .NET-only. The Node host's ArcApplication.createBuilder authentication option above already registers microsoftIdentityPlatform() for local development; see /arc/backend/typescript/identity/local-development/ for its trust boundary.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:
- Without identity headers, protected commands and queries must reject access.
- With a valid local principal but no
Librarianrole, they must still reject access. - With an authenticated principal carrying
Librarian(userRolesin the header fixture), list authors and register one successfully. - 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.
Look back at what you built
Section titled “Look back at what you built”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.