ADR 0009: Centralized JWT Claims Architecture and Validation Strategy
Author: Emir Boyacı • Scope: library-core
1. Context and Problem Statement
Section titled “1. Context and Problem Statement”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.
2. Decision Drivers
Section titled “2. Decision Drivers”- 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.
3. Considered Options
Section titled “3. Considered Options”- 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
SecurityContextinlibrary-core.
4. Decision Outcome
Section titled “4. Decision Outcome”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.
4.1. Visual Architecture Slice
Section titled “4.1. Visual Architecture Slice”The dynamic flow below illustrates how caller claims flow from Keycloak through the security filter chain into the request-scoped application context:
4.2. Implementation Mechanics
Section titled “4.2. Implementation Mechanics”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).
2. Request-Scoped Security Abstraction
Section titled “2. Request-Scoped Security Abstraction”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")@RequiredArgsConstructorpublic 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)andscopeAttributes.getAttribute(attributeName)throwMissingRequiredAttributeExceptionif the scope or claim is missing.library-core’sGlobalExceptionHandlerinterceptsMissingRequiredAttributeException, maps it toResponseCode.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 returnsOptional<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 viaAirCommerceSecurityContextHolder.get():@EventListener@RunAsSystempublic 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 passScopeAttributesexplicitly as a method argument:@RestController@RequiredArgsConstructorpublic class OrderController {private final AirCommerceSecurityContext securityContext;private final AsyncOrderService asyncOrderService;@PostMapping("/async")public ResponseEntity<Void> processAsync() {// Resolve attributes on main HTTP threadScopeAttributes posScope = securityContext.getScopeAttributes("pos");// Pass scope explicitly to worker thread poolasyncOrderService.processInBackground(posScope);return ResponseEntity.accepted().build();}}
5. Pros and Cons of the Options
Section titled “5. Pros and Cons of the Options”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.
Option 2: Flat Claim Mapping in Keycloak
Section titled “Option 2: Flat Claim Mapping in Keycloak”- 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.,
posvs.auditvs.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.
6. Validation and Verification Strategy
Section titled “6. Validation and Verification Strategy”- POJO Unit Testing:
AirCommerceSecurityContextandScopeAttributesare 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
@WebMvcTestverify that accessing nonexistent mandatory claims throwsMissingRequiredAttributeExceptionand translates into an HTTP 403 response withAUTHORIZATION_FAILED. - Shared Test Harness Support: Test cases leverage
library-test-support(BaseControllerTest,@WithMockUser) to populate mock security contexts during integration tests.
7. Migration and Rollout Consequences
Section titled “7. Migration and Rollout Consequences”- Microservice Upgrades: Microservices upgrading to the
library-coreversion introduced in PR #38 must remove legacy local JWT parsing utilities and injectAirCommerceSecurityContext. - Asynchronous Task Audit: Existing background listeners and
@Asyncinvocations must be audited to apply@RunAsSystemor passScopeAttributesas method parameters to avoidScopeNotActiveException. - Keycloak Infrastructure: The Keycloak Terraform module (
keycloak_aircommerce_test) must be deployed with the nested scope mapper definitions before microservices enforce mandatory claim checks.
8. Links and Traceability
Section titled “8. Links and Traceability”- Pull Request: AirCommerce/library-core#38
- ADR Format: Michael Nygard ADR Format
- Core Library: Core Library Documentation
- Affected Services: