تخطي إلى المحتوى
Korur
العودة إلى الحالات

Issuer-Bound Authorization: One API Enforcing Separate Trust Boundaries for Staff, Customers and External Recipients

Each realm has its own security chain and token validator that refuses to start on a wrong issuer, a role matrix per realm, and single-use access codes bound to one offer.

How does one API serve employees, customers and people who have never had an account, without one group ever borrowing the rights of another? For Fepatex, a B2B supplier whose clients include companies in defence and automotive manufacturing, Korur built the answer into the API itself: every route belongs to exactly one trust boundary, every boundary accepts tokens from exactly one issuer, every handler declares the minimum role it needs, and an external recipient gets a single-use code that opens one offer and nothing else.

Client
Fepatex B.V.
Website
fepatex.nl
Engagement
API security architecture and implementation
Trust boundaries
Staff, customers, external recipients
Default
Deny: unmatched routes and unannotated handlers are refused
Stack
Spring Boot, Spring Security, Keycloak
Industry
B2B supplier

Context

Korur built and operates the Fepatex platform: one Spring Boot API behind five applications. Employees work in the staff portal. Customers and the contact persons of customer organisations use the client portal and the webshop. Offers go out to people at customer organisations who often have no account at all, and who must still be able to read and accept the offer that was sent to them.

Sign-in for employees and customers happens in two separate Keycloak realms, described in the companion case on segregated identity domains. A separate sign-in is only half of a boundary. The other half is the API: if it accepts a customer's token on a staff route, or lets a contact person act in an organisation they do not belong to, the separation at sign-in is worth nothing. This case describes how the API enforces those boundaries on every request.

The problem

Most API authorization failures are not broken cryptography. They are a route nobody remembered to protect, a token accepted from the wrong issuer, a role compared against the wrong organisation, or a link that grants more than it should. On a platform that holds customer organisations, dossiers, offers and the personal data of their contacts, each of those is a data breach waiting for someone to try it.

  • Cross-boundary tokens: a valid customer token presented to a staff route, or the reverse. Both tokens are genuine and correctly signed; only the issuer tells them apart.
  • Forgotten routes: a new endpoint added without an access rule and therefore open to anyone who finds it.
  • Privilege escalation: a user who assigns themselves a higher role, or the last administrator of an organisation demoting themselves and locking everyone out.
  • Cross-organisation access: a contact person with a high role in one customer organisation acting with that role in another organisation where they hold a low one.
  • Guessable or reusable offer links: an offer sent to an external recipient that can be opened by anyone who obtains the link, opened again after it was used, or brute-forced.
  • Exposed operations endpoints: health and metrics endpoints answering on the public port.

Architecture

The API is a stateless OAuth 2.0 resource server. It keeps no session; every request carries a bearer token and is judged on its own. The routes are split into groups, and each group is handled by its own Spring Security filter chain. A chain decides two things: which tokens it accepts, and what an accepted token may reach.

Filter chains of the API, in the order they are consulted
ChainRoutesAcceptsResult
OperationsHealth and metrics, on a separate management port onlyNo token; the port is reachable only inside the clusterPermitted on the management port; on the public port these paths fall through and are refused
StaffStaff routesTokens from the staff realm's issuer onlyAuthenticated, then role-checked per handler
CustomerCustomer routesTokens from the customer realm's issuer onlyAuthenticated, then checked per organisation and role
PublicOffer access, payment webhook, API descriptionNo token required; a token that is present must come from the customer issuerPermitted, with each handler enforcing its own checks
FallbackEverything elseNothingDenied

Each of the two realms has exactly one token decoder in the application, bound to that realm's issuer. The staff chain uses only the staff decoder and the customer chain only the customer decoder. A customer token on a staff route therefore fails validation outright: its issuer is not the one the chain trusts, whatever roles it claims.

Authentication answers who is calling. Authorization is a second, independent layer inside the application. The API keeps its own record of every employee, customer user and contact person, with their status and role, keyed on the subject of the token. On each request an interceptor loads that record and compares it with the minimum role the handler declares. Roles are therefore held and changed in the application, where a change takes effect on the next request, rather than baked into tokens that remain valid until they expire.

External recipients of an offer sit outside both realms. They receive a single-use access code by email and exchange it, together with their email address, for a short-lived token that the API issues itself and that names exactly one offer.

What we built

Each key choice is recorded below with its reason and the alternative we rejected.

Decision 1

Decision
One filter chain and one issuer-bound token decoder per trust boundary.
Why
Binding a route group to a single issuer makes the boundary structural: there is no code path in which a customer token is evaluated on a staff route, so there is no role check that could be got wrong. Each decoder is a named component, so a test can replace one boundary's decoder while the others stay real and prove the boundaries independently.
Alternative rejected
One chain that accepts tokens from both issuers and separates staff from customers by role claims. Less configuration, but every handler would then depend on claims being checked correctly, and one missed check would cross the boundary.

Decision 2

Decision
Validate the issuers at startup, not at the first request.
Why
The decoders fetch each issuer's discovery document while the application starts. A wrong or unreachable issuer stops the deployment before it serves a single request, and the rollout keeps the previous version running. A misconfiguration becomes a failed release that an engineer sees, instead of a production API that rejects or, worse, mis-handles real users.
Alternative rejected
Lazy decoders that resolve the issuer on first use. The application would start healthy and fail in front of users.

Decision 3

Decision
Fail closed twice: a fallback chain that denies every unmatched route, and interceptors that refuse every handler without an access annotation.
Why
A new endpoint must never be public because someone forgot it. At the route level, anything outside the known groups is denied. At the handler level, every staff and customer handler carries an annotation with its minimum role, and an unannotated handler is answered with 403, apart from the two self-service endpoints a new employee needs to complete the first sign-in. Forgetting the annotation produces a visible failure in testing, not an open door in production.
Alternative rejected
Allow by default and protect the sensitive routes. It is how most APIs start, and it makes every omission a vulnerability.

Decision 4

Decision
Role matrices per realm, held in the application: viewer, contributor, manager and administrator.
Why
The same four levels exist for staff and for customer users, but they are separate matrices with separate rules. Viewers read; contributors create and edit; managers may also delete and assign roles below the administrator; administrators carry out destructive and structural operations. Nobody can assign a role above their own level or promote themselves, and the last administrator of an organisation cannot demote themselves. That last check reads the administrator count under a database row lock, so two simultaneous demotions cannot both pass and leave an organisation without an administrator.
Alternative rejected
Roles as Keycloak realm roles read from the token. A role change would wait for token expiry, and roles that differ per customer organisation cannot be expressed in a flat realm role.

Decision 5

Decision
Customer authorization scoped to the organisation of the request.
Why
A contact person can belong to several customer organisations with a different role in each. Every customer request names its organisation, and the API checks, in order, that the user is active, that they are an active contact person of that organisation, that the organisation has portal access, and only then that their role in that organisation meets the handler's minimum. The role is never taken as the highest role across all organisations, which closes the path to cross-organisation privilege escalation.
Alternative rejected
A single role per user across all organisations. Simpler, but a manager in one organisation would be a manager everywhere.

Decision 6

Decision
Single-use, offer-bound access codes for external recipients.
Why
An external recipient needs to open one offer, for a limited time, without an account. The code is drawn from a cryptographically strong random generator, 16 characters from an alphabet without look-alike characters, which gives about 94 bits of entropy. It is bound to one offer and one email address, is valid for 14 days, and is stored only as a bcrypt hash; the plaintext exists only in the email. A successful redemption marks the code as used, so it cannot be replayed. Three wrong attempts revoke the code. New codes can be requested at most once an hour and five times per offer, so a lockout cannot be reset by asking for a fresh code.
Alternative rejected
A long random link that opens the offer directly. Anyone who obtains a forwarded email or a browser history can open it, as often as they like, for as long as it lives.

Decision 7

Decision
A short-lived, offer-scoped token after redemption, with a rotating refresh token.
Why
After the code is redeemed, the API issues its own signed access token whose subject is the offer, valid for 30 minutes, and an opaque refresh token valid for 7 days that is stored only as a keyed hash and replaced on every use. The access token can be checked without a database call, while the refresh token can be revoked and cannot be replayed. The token cannot reach another offer, because the offer is its subject.
Alternative rejected
Creating a temporary customer account for each recipient. It would fill the customer realm with accounts nobody manages and give a one-time reader a lasting identity.

Decision 8

Decision
Operations endpoints on a separate management port that no ingress routes.
Why
Prometheus and the Kubernetes probes need health and metrics without a token. Serving them on their own port, which exists only inside the cluster, means they are never exposed publicly; on the public port the same paths fall through to the fallback chain and are refused. An integration test checks both sides.
Alternative rejected
Actuator endpoints on the public port behind authentication. One misconfigured rule would expose internal metrics to the internet.
@Bean
@Order(1)
public SecurityFilterChain staffChain(HttpSecurity http,
        @Qualifier(STAFF_DECODER) JwtDecoder staffDecoder) throws Exception {
    return http
            .securityMatcher("/staff/**")
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .oauth2ResourceServer(o -> o.jwt(jwt -> jwt.decoder(staffDecoder)))
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .build();
}

@Bean
@Order(4)
public SecurityFilterChain fallbackChain(HttpSecurity http) throws Exception {
    return http
            .securityMatcher("/**")
            .authorizeHttpRequests(auth -> auth.anyRequest().denyAll())
            .build();
}
Excerpt of the filter chain layout, with route patterns and bean names generalised

Evidence

The boundaries are defined in code and pinned by tests in the same code base. The table lists what each layer guarantees and how it is checked.

Authorization layers and how they are verified
LayerGuaranteeVerified by
Filter chainsEach route group accepts one issuer; unmatched routes are deniedSecurity configuration integration test: a token from the other realm is answered with 401, an unknown path with 404
Management portHealth and metrics answer only on the internal portManagement port integration test: 200 inside, refused on the public port
Staff interceptorActive employee with at least the declared role; unannotated handlers refusedInterceptor unit tests
Customer interceptorActive user, organisation membership, portal access, role in that organisationInterceptor unit tests
Role assignmentNo self-promotion, no assignment above one's own level, last administrator protected under a row lockValidator tests and the locked repository query
Offer access codesSingle use, bound to one offer and address, revoked after three failures, renewal throttledAccess code validator and failure handling tests
  1. A request arrives; the first filter chain whose routes match takes it.
  2. The chain validates the bearer token against the one issuer it trusts, or denies the request.
  3. The interceptor loads the caller's record from the application and checks status, organisation and role against the handler's annotation.
  4. Only then does the handler run, receiving the already verified caller.

Outcome

Fepatex's API enforces three trust boundaries in one code base. Staff and customer tokens cannot cross into each other's routes, because each route group trusts one issuer only. Every handler states the minimum role it requires, and a handler that forgets to state it is refused. Customer roles apply only within the organisation of the request. External recipients open the one offer they were sent, once per code, without receiving an account.

For Fepatex's own clients, this means a clear answer to an audit question that is often hard to answer: who can reach which data through the API, and what stops everyone else. The answer is in the security configuration and its tests, not in a policy document.

What we would do next

  • Publish an access matrix generated from the handler annotations, so the documentation of who may call what can never drift from the code.
  • Add a coverage test that fails the build whenever a staff or customer handler lacks an access annotation, so the default deny is proven at build time and not only at request time.
  • Forward authorization denials and access code revocations to central monitoring, so repeated attempts against one boundary raise an alert.
  • Review the lifetime of external recipients' refresh tokens against how long offers stay open in practice.

Stack

  • Spring Boot
  • Spring Security
  • Keycloak
  • OAuth 2.0
  • JSON Web Tokens
  • PostgreSQL
  • bcrypt

هل تريد تأمين عملك أيضًا؟

محادثة بدون التزام. سعر ثابت.

هل تسمح لنا بأن نقيس كيف وصلت إلى هنا؟

نستخدم ملفات تعريف الارتباط التحليلية لنعرف أي صفحة تؤدي عملها وأي إعلان قادك إلى هنا. وإذا رفضت، فسيعمل الموقع تمامًا كما هو ولن نضع أي ملفات تعريف ارتباط تحليلية. سياسة ملفات تعريف الارتباط