Skip to content

ADR 0009: Centralized JWT Claims Architecture and Validation Strategy

Author: Emir Boyacı • Scope: library-core

The AirCommerce microservices ecosystem requires consuming both shared and isolated user attributes—such as distribution channel, agencyCode, agentId, and Point of Sale (POS) metadata—originating from Keycloak Identity and Access Management (IAM). As downstream services process airline retailing operations (such as NDC 24.x requests transformed into canonical Order operations), these identity and channel claims must be reliably propagated across services via Core Library (library-core).

Previously, microservices suffered from several critical operational challenges:

  • Scattered Parsing: Individual microservices wrote ad-hoc boilerplate logic to unpack deeply nested JSON claims from raw JWT token strings.
  • Redundant Validation: Validating mandatory claims locally inside each service led to severe code duplication, inconsistent validation behavior, and divergence from Keycloak as the authoritative Identity Provider (IdP).
  • Inconsistent Error Handling: When a required claim was missing from a token, services responded inconsistently—often failing with unhandled null pointer exceptions or generic HTTP 500 Internal Server Errors rather than communicating an authorization denial.

A standardized, enterprise-grade architecture was required to validate, bridge, and consume structured JWT claims centrally in library-core.

  • Security & Authorization: Missing required identity claims must semantically represent an authorization failure, rejecting unprivileged requests with an explicit HTTP 403 Forbidden.
  • DRY (Don’t Repeat Yourself): Identity attribute validation rules must reside in a single source of truth at the IdP boundary, preventing distributed rule divergence across microservices.
  • Developer Experience (DX): Service engineers need a strongly-typed, request-scoped abstraction (AirCommerceSecurityContext) to access verified claims without manual JSON parsing.
  • Performance: JWT claims must be parsed and structured exactly once per HTTP request within the Spring Security filter chain and held in memory for downstream evaluation.
  • Option 1: Validate and parse claims locally in every microservice.
  • Option 2: Map claims flatly in Keycloak and inject via standard Spring Security JwtAuthenticationToken.
  • Option 3 (Chosen): Scope-based nested mapping in Keycloak + Centralized SecurityContext in library-core.

We chose Option 3: configuring scope-based nested claim mappings in Keycloak (attributes.<scope>.<attribute>) via Terraform and introducing a centralized, request-scoped security context abstraction (AirCommerceSecurityContext) in library-core.

The dynamic flow below illustrates how caller claims flow from Keycloak through the security filter chain into the request-scoped application context:

1. Identity Provider as the Source of Truth

Section titled “1. Identity Provider as the Source of Truth”

Keycloak enforces validation of mandatory user attributes at token issuance using required_for_roles. Claims are mapped into the JWT access token using structured scope paths (attributes.<scope>.<attribute>) via Keycloak User Attribute Protocol Mappers configured in Terraform (keycloak_aircommerce_test).

library-core provides AirCommerceSecurityContext as a @RequestScope bean, backed by a ThreadLocal bridge (AirCommerceSecurityContextHolder) populated by the Spring Security filter chain during token validation. Downstream microservices inject AirCommerceSecurityContext directly:

@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderController {
private final AirCommerceSecurityContext securityContext;
private final OrderService orderService;
@PostMapping
public ResponseEntity<OrderResponse> createOrder(@RequestBody OrderRequest request) {
// 1. Resolve scope attributes (throws MissingRequiredAttributeException / HTTP 403 if missing)
ScopeAttributes posScope = securityContext.getScopeAttributes("pos");
// 2. Read mandatory attributes (throws HTTP 403 if missing)
String channel = posScope.getAttribute("channel");
String agencyCode = posScope.getAttribute("agencyCode");
// 3. Read optional attributes with fallback defaults
String agentId = posScope.getOptionalAttribute("agentId").orElse("SYSTEM");
return ResponseEntity.ok(orderService.process(request, channel, agencyCode, agentId));
}
}

3. Mandatory by Default and Semantic Error Handling

Section titled “3. Mandatory by Default and Semantic Error Handling”

Attribute access follows a mandatory-by-default convention:

  • context.getScopeAttributes(scopeName) and scopeAttributes.getAttribute(attributeName) throw MissingRequiredAttributeException if the scope or claim is missing.
  • library-core’s GlobalExceptionHandler intercepts MissingRequiredAttributeException, maps it to ResponseCode.AUTHORIZATION_FAILED, and responds with HTTP 403 Forbidden. This correctly signals that the caller is authenticated but lacks the clearance or profile attributes required for the endpoint.
  • For optional claims, developers explicitly call getOptionalAttribute(attributeName), which returns Optional<String>.

4. Background Tasks and Asynchronous Execution

Section titled “4. Background Tasks and Asynchronous Execution”

Because AirCommerceSecurityContext is scoped to an active HTTP request (@RequestScope), resolving the bean on a background worker thread fails with ScopeNotActiveException. Furthermore, the internal ThreadLocal is intentionally isolated from thread pools to avoid context leakage.

To handle non-request threads, library-core enforces two clear execution patterns:

  • System-Triggered Tasks (@EventListener, @Scheduled, RabbitMQ Listeners): Annotate the handler method with @RunAsSystem. The aspect sets up a privileged system security context, and code retrieves it directly via AirCommerceSecurityContextHolder.get():

    @EventListener
    @RunAsSystem
    public void handleOrderEvent(OrderChangedEvent event) {
    AirCommerceSecurityContext context = AirCommerceSecurityContextHolder.get();
    // Execute maintenance logic under system authority
    }
  • User-Triggered Asynchronous Tasks (@Async): When an active HTTP request triggers an asynchronous method, the calling thread must resolve and pass ScopeAttributes explicitly as a method argument:

    @RestController
    @RequiredArgsConstructor
    public class OrderController {
    private final AirCommerceSecurityContext securityContext;
    private final AsyncOrderService asyncOrderService;
    @PostMapping("/async")
    public ResponseEntity<Void> processAsync() {
    // Resolve attributes on main HTTP thread
    ScopeAttributes posScope = securityContext.getScopeAttributes("pos");
    // Pass scope explicitly to worker thread pool
    asyncOrderService.processInBackground(posScope);
    return ResponseEntity.accepted().build();
    }
    }

Option 1: Local Validation in Microservices

Section titled “Option 1: Local Validation in Microservices”
  • Good: Completely decoupled from specific Keycloak protocol mapper structures.
  • Bad: Severe code duplication across every microservice. High risk of inconsistent validation rules. Unhandled missing claims cause generic HTTP 500 errors.
  • Good: Simple single-level claim extraction (jwt.getClaimAsString("channel")).
  • Bad: Flat claim namespaces lead to naming collisions across different business scopes. Unable to partition claims cleanly by boundary (e.g., pos vs. audit vs. partner).

Option 3 (Chosen): Scope-Based Nested Mapping and Centralized Security Context

Section titled “Option 3 (Chosen): Scope-Based Nested Mapping and Centralized Security Context”
  • Good: Eliminates JSON boilerplate across all microservices. Enforces a single source of truth for attribute validation in Keycloak. Guarantees uniform semantic HTTP 403 Forbidden handling for missing claims. Cleanly isolates claim domains using nested scope trees (attributes.<scope>.<attribute>).
  • Bad: Introduces structural coupling between Keycloak’s Terraform token configuration and library-core’s JWT claim parser.
  • POJO Unit Testing: AirCommerceSecurityContext and ScopeAttributes are pure Java objects that can be instantiated with mock JWTs and in-memory claim maps in standard JUnit 5 tests without starting a Spring application context or external Keycloak container.
  • Exception Mapping Verification: Controller tests using @WebMvcTest verify that accessing nonexistent mandatory claims throws MissingRequiredAttributeException and translates into an HTTP 403 response with AUTHORIZATION_FAILED.
  • Shared Test Harness Support: Test cases leverage library-test-support (BaseControllerTest, @WithMockUser) to populate mock security contexts during integration tests.
  • Microservice Upgrades: Microservices upgrading to the library-core version introduced in PR #38 must remove legacy local JWT parsing utilities and inject AirCommerceSecurityContext.
  • Asynchronous Task Audit: Existing background listeners and @Async invocations must be audited to apply @RunAsSystem or pass ScopeAttributes as method parameters to avoid ScopeNotActiveException.
  • Keycloak Infrastructure: The Keycloak Terraform module (keycloak_aircommerce_test) must be deployed with the nested scope mapper definitions before microservices enforce mandatory claim checks.