Access Control Plugin
Overview
The Access Control Plugin is a plugin that enforces security rules during JSON:API request processing without altering the core execution flow. It evaluates access requirements at well-defined stages of the request lifecycle and conditionally allows, anonymizes, or short-circuits parts of the request or response based on the resolved principal context.
To enable the Access Control plugin, add the following dependency:
<dependency>
<groupId>pro.api4</groupId>
<artifactId>jsonapi4j-ac-plugin</artifactId>
<version>${jsonapi4j.version}</version>
</dependency>
If you’re using Spring Boot or Quarkus, the plugin is auto-configured with default values.
Access control is applied at two points of the request processing pipeline:
- Inbound evaluation – before any data is fetched (pre-retrieval stage). Rules are evaluated against the incoming
JsonApiRequest. If access is denied, downstream execution is skipped and the response is safely anonymized. - Outbound evaluation – after data has been fetched and the JSON:API document has been composed (post-retrieval stage). Rules are evaluated per resource and relationship element, allowing fine-grained control over visibility of attributes, meta, links, and relationship identifiers.
The plugin derives its rules from @AccessControl annotations placed on operations, resources, relationships, attributes, or individual fields.
During execution, it traverses JSON:API structures using explicit visitor points and applies access decisions consistently across resource objects and resource identifier objects.
This design enables declarative, centralized security policies while keeping domain logic and request handling clean, predictable, and specification-compliant.
Evaluation stages
As it was mentioned above access control evaluation is performed twice during the request lifecycle - during the inbound and outbound stages.
Inbound Evaluation Stage
During the inbound stage, the JsonApi4j application has received a request but has not yet fetched any data from downstream sources.
Access control rules are evaluated against the JsonApiRequest since no other data is available at this point.
If access control requirements are not met, data fetching is skipped, and the data field in the response will be fully anonymized.
Inbound access control requirements can be defined on an operations level by placing @AccessControl annotation on top of the class declaration. When implementing ResourceOperations<RESOURCE_DTO>, ToOneRelationshipOperations<RESOURCE_DTO, RELATIONSHIP_DTO> or ToManyRelationshipOperations<RESOURCE_DTO, RELATIONSHIP_DTO> interfaces @AccessControl annotation must be placed above the corresponding method.
Outbound Evaluation Stage
The outbound stage occurs after data has been fetched from the data source, the response document has been composed, and right before it is sent to the client. At this point, access control rules are evaluated for each JSON:API Resource Object or Resource Identifier Object within the generated JSON:API document.
Resource Documents
Resource documents typically contain full JSON:API Resource Objects.
Access control requirements can be defined for:
- Entire Resource Object - if requirements are not met, the whole resource is anonymized.
@AccessControlannotation must be placed on top of the class that implementsResource<RESOURCE_DTO>interface. - Specific members (e.g.,
attributes,links,meta) - if requirements are not met, only those members are anonymized.@AccessControlannotation must be placed above theresolveAttributes(...),resolveResourceLinks(...)or other methods accordingly. - Individual
attributefields - if requirements are not met, only the affected fields are anonymized.@AccessControlannotation must be placed for the needed field.
Relationship Documents
Relationship documents contain only Resource Identifier Objects. Access control rules can be defined for:
- Entire Resource Identifier Object - if requirements are not met, the entire resource identifier will be anonymized.
@AccessControlannotation must be placed on top of the class that implementsToOneRelationship<RELATIONSHIP_DTO>orToManyRelationship<RELATIONSHIP_DTO>interface. - Specific members (e.g.,
meta) - if requirements are not met, only those members will be anonymized.@AccessControlannotation must be placed above theresolveResourceIdentifierMeta(...)method.
What a denial returns
For a GET, a denied request returns 200 with the restricted data omitted rather than an error — a 403
would fail the whole response including the parts the caller is allowed to see, and would break compound
documents.
For everything else, a denied request returns 403 with an error code naming what failed:
| Requirement that failed | Error code |
|---|---|
entitlements |
INSUFFICIENT_ENTITLEMENTS |
scopes |
INSUFFICIENT_SCOPES |
authenticated, ownership, policy |
FORBIDDEN |
Entitlements and scopes are named because they tell a caller different things — one needs different credentials, the other a differently-scoped token. Ownership stays generic deliberately: reporting “you are not the owner” would confirm that the resource exists and that somebody else holds it. A policy is application code with no code of its own to report.
A custom evaluator can report any ErrorCode it likes, including its own — see
Overriding the AccessControlEvaluator.
Access Control Requirements
By default, JsonApi4j does not enforce any access control (i.e., all requests are allowed). However, you can configure and enforce access control rules for either or both stages - inbound and outbound - depending on your security and data exposure requirements.
There are five types of access control requirements, which can be combined in any way as needed:
- Authentication requirement - verifies whether the request is made on behalf of an authenticated client or user. This can be used to restrict anonymous access.
- Entitlement requirement - verifies whether the client or user holds a given entitlement. Entitlements are plain, unordered labels that your application defines and your principal source supplies - any string works.
DefaultEntitlementsoffers PARTNER, ADMIN and ROOT_ADMIN as ready-made constants, but they carry no built-in ranking, and there is no label meaning “everyone” or “nobody” - omit the requirement to demand nothing, and name an entitlement no principal carries to deny everyone. See more details below. - OAuth2 scope(s) requirement - verifies whether the request was authorized to access user data protected by certain OAuth2 scopes. This information is typically embedded within the JWT access token. Declared with the same two-level clause structure as entitlements. See more details below.
- Ownership requirement - ensures that the requested resource belongs to the client or user making the request. This is typically used for APIs where users are only allowed to view their own data, but not others’.
- Policy requirement - decides the rule in code, for anything the four declarative forms cannot express - reading the caller’s attributes, branching on the operation being performed, or comparing the caller against the resource being returned. See more details below.
If any of the specified requirements are not met, the corresponding section - or the entire object - will be anonymized.
Setting Principal Context
By default, the plugin uses the DefaultPrincipalResolver, which relies on the following HTTP headers to resolve the current authentication context:
X-Authenticated-User-Id- identifies whether the request is sent on behalf of an authenticated client or user. Considered authenticated if the value is not null or blank. Also used for ownership checks.X-Authenticated-Client-Entitlements- defines the principal’s entitlements, as a space-separated list. Any string works;DefaultEntitlementsships PARTNER, ADMIN and ROOT_ADMIN as constants purely for convenience.X-Authenticated-User-Granted-Scopes- specifies the OAuth2 scopes granted to the client by the user. This should be a space-separated string.
This is not the only option. JsonApi4j also ships resolvers that build the principal from a JWT — either by
decoding the Authorization header directly, or by reading claims Spring Security or Quarkus OIDC have
already verified — and you can implement PrincipalResolver yourself for anything else. See
Principal Resolution for the full list, how to choose between them, and how to map
your provider’s claims.
If you use entitlement requirements together with a JWT resolver, note that you must name the claim that carries the entitlement — JWT defines no standard one, and an unresolved entitlement denies every entitlement-guarded operation. This is covered in Entitlements need an explicit claim.
The resolved principal context is then used by the framework during both inbound and outbound access control evaluations.
Setting Access Requirements
There is one annotation that defines all access control requirements in one place — @AccessControl.
It encapsulates rules for all currently supported dimensions: authenticated, scopes, entitlements, ownership, and policy.
Entitlements Are Unordered Labels
Entitlements are matched by name, not by rank. A principal holding ADMIN does not satisfy a requirement for
PARTNER — it satisfies a requirement for ADMIN and nothing else. Grant a principal every entitlement it needs
rather than expecting a “higher” one to cover the others.
A requirement is built from @EntitlementsGroup clauses. Each clause quantifies over entitlement names:
| Clause mode | Satisfied when the caller holds |
|---|---|
ANY_OF (default) |
at least one of the listed entitlements |
ALL_OF |
all of the listed entitlements |
NONE_OF |
none of the listed entitlements |
@AccessControlEntitlements then quantifies over the clauses, using the same three modes — ALL_OF by
default. That gives two levels:
@AccessControl(entitlements = @AccessControlEntitlements(
description = "internal support staff, or a partner integration",
mode = AccessControlEntitlements.Mode.ANY_OF,
value = {
@EntitlementsGroup(value = {ADMIN, "SUPPORT"}, mode = EntitlementsGroup.Mode.ALL_OF),
@EntitlementsGroup(value = {PARTNER, "INTEGRATOR"}, mode = EntitlementsGroup.Mode.ALL_OF)
}))
which reads as (ADMIN and SUPPORT) or (PARTNER and INTEGRATOR). ADMIN and PARTNER come from
DefaultEntitlements; SUPPORT and INTEGRATOR are plain strings — any label your principal source produces works.
The simple case stays short — a single clause with the default ANY_OF:
@AccessControl(entitlements = @AccessControlEntitlements(@EntitlementsGroup(ADMIN)))
Omit entitlements entirely to declare no requirement. An empty @EntitlementsGroup({}) is rejected at
startup, so a requirement that can never be satisfied fails on boot rather than silently denying every
request.
description is optional and quoted back when access is denied, so a log line explains why the
requirement exists rather than only naming entitlements:
DEBUG Access denied: 'internal support staff, or a partner integration'
(ANY_OF[ALL_OF[ADMIN, SUPPORT], ALL_OF[PARTNER, INTEGRATOR]]) is required,
but the authenticated principal carries [PARTNER].
Scopes Use the Same Structure
Scopes are declared exactly like entitlements — @ScopesGroup clauses combined by
@AccessControlScopes, with the same three modes. Matching is by exact name.
@AccessControl(scopes = @AccessControlScopes(
description = "read access to profiles, or full admin access",
mode = AccessControlScopes.Mode.ANY_OF,
value = {
@ScopesGroup({"users.read", "profiles.read"}),
@ScopesGroup("admin.full")
}))
which reads as (users.read and profiles.read) or admin.full. The simple case stays short:
@AccessControl(scopes = @AccessControlScopes(@ScopesGroup("users.sensitive.read")))
| Clause mode | Satisfied when the caller was granted |
|---|---|
ALL_OF (default) |
all of the listed scopes |
ANY_OF |
at least one of the listed scopes |
The clause default is ALL_OF rather than entitlements’ ANY_OF, because a scope requirement normally asks
for every scope it lists.
For rules this cannot express — weighing scopes together with the operation, the resource, or the caller’s
attributes — use a policy; it reads the granted scopes from
context.principal().authenticatedClientScopes().
Where to Place @AccessControl
| Target | Placement | Effect when requirements are not met |
|---|---|---|
| Operation (inbound) | On the operation method (e.g. create(), readById()) |
Data fetching is skipped; response data is anonymized |
| Entire Resource Object | On the class implementing Resource<T> |
The whole resource object is anonymized |
| Resource attributes | On resolveAttributes() method or on the attributes class |
Attributes section is anonymized |
| Resource links | On resolveResourceLinks() method |
Links section is anonymized |
| Resource meta | On resolveResourceMeta() method |
Meta section is anonymized |
| Individual attribute field | On the field in the attributes class | Only the affected field is anonymized |
| Nested object | On a class held by the attributes, or on its fields | Applies wherever an instance of that class appears, at any depth |
| Collection, array or map element | On the element class, or on its fields | Applied per element; an element denied entirely is dropped from the container |
| A runtime type more specific than the field’s declared type | On the runtime class | Applies — requirements come from the object present, not from how the field was declared |
| Entire Relationship | On the class implementing ToOneRelationship<T> or ToManyRelationship<T> |
The entire resource identifier is anonymized |
| Relationship meta | On resolveResourceIdentifierMeta() method |
Meta section of the resource identifier is anonymized |
Ownership: Inbound vs. Outbound
The ownership setting works differently depending on the evaluation stage:
| Stage | Property | How it works |
|---|---|---|
| Inbound (pre-retrieval) | ownerIdExtractor |
A class that extracts the owner ID from the incoming request (e.g. from the URL path) |
| Outbound (post-retrieval) | ownerIdFieldPath |
A field path pointing to the owner ID in the JSON:API response (e.g. "id") |
The examples below show these placements at work.
Policies: Deciding Access in Code
Each declarative requirement has a fixed shape — authenticated is a flag, entitlements is two levels of
name matching, scopes is an expression, ownership is an id comparison. When a rule doesn’t fit any of
them, write it as code:
public