Application security

API security in payment infrastructure: BOLA, OAuth 2.1 and FAPI 2.0

Most breaches in the financial cloud do not start with a WAF that was broken, but with a single endpoint that returned someone else's object. API security is mostly authorisation security.

Article summary
  • BOLA and BFLA are the most common categories in APIs — and no library fixes them, only the authorisation model does.
  • mTLS identifies a client, not a user: you also need OAuth 2.1 with a narrow scope for each operation.
  • FAPI 2.0 defines request signing, nonce and token validation — these are requirements, not "nice to have".
  • Idempotency is a security control: without an Idempotency-Key, a retry becomes a double charge.
API traffic — an illustration of request flow through an API gateway

Why the API is the attack surface

When I worked on the acquiring side, payment infrastructure looked different. A batch file over SFTP once a day, a SOAP interface with WS-Security, an allowlist of IP addresses, and a schema agreed with the provider. The API had a marginal role: a daily report and a status check.

Today the endpoint is the product. Acquiring, wallets, instant transfers such as PayNow, payment terminals and mobile apps — they all speak REST and JSON. Open banking turned the account itself into a resource exposed through an API, with consent granted by the customer rather than the bank. Once the API is the product, it is also the primary attack surface.

The difference is not only the protocol. A batch file is one channel with mutual authentication and a schema known in advance. An API is hundreds of endpoints, several versions running side by side, clients of every kind and keys distributed to partners. Every endpoint that accepts an identifier — account, instruction, refund, customer — is an authorisation boundary. Most of the incidents I know did not start with an authentication bypass but with a question nobody asked: who owns this object.

OWASP API Security Top 10, 2023

The OWASP list is organised by type of failure, not by type of component. Here are nine of its categories:

CategoryOne-line meaning
API1:2023 — Broken Object Level Authorisation (BOLA)Reaching an object by identifier without checking that it belongs to the caller or that the caller may act on it.
API2:2023 — Broken AuthenticationWeak or missing authentication: hard-coded keys, tokens that never expire, a flow that is easy to bypass.
API3:2023 — Broken Object Property Level AuthorizationExposure or modification of individual fields — balance, status, owner — that were not meant for this caller.
API4:2023 — Unrestricted Resource ConsumptionNo limits on the resources a single request, or a run of requests, consumes: size, rate, compute.
API5:2023 — Broken Function Level AuthorizationAn administrative or internal action reachable by someone not authorised to perform it, even when the object is theirs.
API6:2023 — Unrestricted Access to Sensitive Business FlowsA sensitive business flow — sign-up, purchase, transfer — that is not protected against automated or repeated use.
API7:2023 — Server Side Request ForgeryFeeding an address into the internal network that the server will fetch on your behalf.
API9:2023 — Improper Inventory ManagementVersions and endpoints that are undocumented or unmonitored, including whatever survived from a previous environment.
API10:2023 — Unsafe Consumption of APIsUnchecked trust in data coming from a third-party API, as if it were our own.

What most of these categories share: the request is legitimate. A valid token, a correct schema, and exactly the same bytes as the real client sends. The weakness is not a bug in parsing but a missing decision, which is why API security is mostly an authorisation programme rather than a firewall programme.

The ninth category belongs here too. You cannot protect an endpoint that is not in the inventory. An old version, an endpoint for one partner left open, a test service in production — these are what most reviews find first.

BOLA: the boundary between authentication and authorisation

Broken object level authorisation is simple to describe and hard to fix systematically. Authentication worked: the token is valid, the signature is correct, the client is real. What was not checked is whether the object belongs to that same client. Authentication answers "who are you"; object authorisation answers "what may you do with this thing". That is where most of the exposure sits.

Here is a classic example in Spring Boot, one that passes every test its author writes for it:

@GetMapping("/accounts/{id}")
public Account getAccount(@PathVariable String id,
                          @AuthenticationPrincipal Jwt jwt) {
    // the token was validated, but the link between account and client was not checked
    return accountRepository.findById(id)
        .orElseThrow(NotFoundException::new);
}

The fix is not "add an if". The fix is to make ownership part of the query:

public interface AccountRepository extends JpaRepository<Account, String> {
    @Query("select a from Account a where a.id = :id and a.ownerId = :owner")
    Optional<Account> findOwnedBy(@Param("id") String id, @Param("owner") String owner);
}

@GetMapping("/accounts/{id}")
public ResponseEntity<Account> getAccount(@PathVariable String id,
                                           @AuthenticationPrincipal Jwt jwt) {
    return accountRepository.findOwnedBy(id, jwt.getSubject())
        .map(ResponseEntity::ok)
        .orElseGet(() -> ResponseEntity.notFound().build());
}

Two notes. The first: ownership is not always one column. A joint account, a power of attorney, a trust and an organisational hierarchy are rules, not a field, which is why in those cases I move the decision into a policy engine such as OPA that reads who the caller is, which object and which action. The second: returning 404 rather than 403 is not a matter of politeness. If "not found" is also returned when there is no permission, the attacker does not learn whether the identifier exists. If you choose 403, choose it consistently for every resource — the inconsistency itself leaks.

IDOR in internal APIs

The mistake I meet again and again is the assumption that an internal API is exempt. A support console, a refund tool, a reconciliation service and a collections tool — they all take an object identifier from a human user, and they all assume someone else checked it. The reconciliation service gets a token with blanket permission because "it needs to read everything". The moment a pod holding such a token is compromised, the internal API becomes a clean lateral path into the data.

The internal network is not a boundary. In Kubernetes every pod reaches every service by internal DNS name, and a service mesh with mTLS gives you workload identity — not object authorisation. An Istio authorisation policy answers "may service A call service B", not "may this support agent see this account". Only the service that holds the data closes that gap, and that is also the basis of any Zero Trust model: there is no trusted network, there is identity and a decision for every request.

Why a WAF does not fix this

Someone once asked me whether this can be blocked in a WAF. The short answer is no. An attack request and a legitimate request share the same path, the same schema, the same valid token and the same body. The only difference is the relationship between identity and ownership — that is, a business fact. A WAF works on syntactic patterns, and there is no pattern that says "this identifier belongs to someone else".

The same holds for schema validation, rate limiting and signature checks: they are all good controls, and all of them are blind to authorisation. Random identifiers are not a control either. A legitimate client receives real identifiers in every response, and another account's identifier leaked from a business partner or a support transcript is a very good starting point.

What does work: a central decision, deny-by-default, and an automated test with a foreign identity.

Authentication: mTLS and OAuth 2.1

Payments have two identity questions, and people often try to answer both with one tool. Who is the client talking to us — the merchant's server, the app in the store, the partner's platform. And who is the user who gave the instruction. One answer is not enough for both, and that is the source of most of the confusion in payment system design.

mTLS as client identity

mTLS is the stable way to identify a client at the transport layer. The client presents a digital certificate in the handshake, the server validates it against a certificate authority (CA) it trusts, and the result is an identity that cannot be forged without the private key. TLS 1.3 closed some of the problems of earlier versions, but it did not remove the need for certificate management: issuance, key rotation and revocation.

RFC 8705 takes this a step further, and it is the document I recommend reading before designing client authentication. It defines client authentication with mTLS against the authorisation server, and also an access token bound to the certificate: the token carries a thumbprint of the certificate (x5t#S256), and the resource server checks that the certificate presented in the handshake is that same certificate. A stolen token becomes worthless without the private key — that is the difference between a bearer token and a sender-constrained one.

OAuth 2.1 for the user

OAuth 2.1 is not a new protocol; it is a consolidation of RFC 6749 and RFC 6750 with the decisions that have become convention: mandatory PKCE on every authorization code flow, removal of the implicit and password grants, exact redirect URI matching, and short-lived access tokens. If you are building a payments API today, there is no good reason to use anything else. A long-standing integration with a password grant is not an aesthetic problem — it is a route that hands the customer's password to parties that should never receive it.

A short-lived token is a control, not a convenience: five minutes is a reasonable default, and refresh with reuse detection lets you spot theft in real time.

scope per operation

scope is coarse authorisation for an operation. It is not object authorisation, but it narrows the surface: a client that reads balances does not need permission to create a payment, and a client that creates instructions does not need permission for refunds. I recommend mapping each endpoint to exactly one scope, and checking it both at the authorisation server during consent and at the resource server on every request. The double check is the difference between an incident and a breach.

It is worth checking aud as well: a token issued for one API should not work against another, even when the same authorisation server issued it. That sounds obvious, and yet I keep meeting it when several services share a public key.

A token request

A realistic request: client authentication with private_key_jwt over mTLS, with PKCE. The certificate is presented in the handshake, so it has no line in the request:

POST /oauth2/token HTTP/1.1
Host: auth.example-pay.sg
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fmerchant.example%2Fcallback
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
&client_id=merchant-4417
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&client_assertion=eyJhbGciOiJQUzI1NiIsImtpZCI6IjIwMjYtMTEifQ...

And the response, as short as it can be:

{
  "access_token": "eyJhbGciOiJFUzI1NiIsImtpZCI6ImF1dGgtMjAyNi0xMSJ9...",
  "token_type": "Bearer",
  "expires_in": 300,
  "scope": "payments:write accounts:balance:read"
}

Inside the token, if it is a JWT, sit sub (the user), aud (the API it was issued for), scope, and cnf with the certificate thumbprint. The first three are what the resource server checks; the fourth prevents the token being passed on.

mTLS identifies a client, not a person

A valid certificate says "this is that company, from this server". It does not say which user gave the instruction, and it does not stop working the moment the client's server is compromised. If the system settles for mTLS alone, anyone with access to the merchant's server acts on behalf of all its customers. Only a user token with the right scope closes that, along with a rule that is not open to debate: the user identity comes from the sub in the token, not from a header the client controls, such as X-User-Id.

FAPI 2.0

FAPI 2.0, the OpenID Foundation's financial profile, is not a new protocol. It narrows the space of OAuth and OIDC options to one that survives a hostile environment: mobile apps, third-party providers and open banking, and clients whose key sits on a device they do not control. The idea holds for any financial system: where money is involved, there is no room for "flexibility" in configuration.

The profile rests on the OpenID Foundation documents, chiefly Part 1 for flows and authentication and Part 2 for authorisation and consent management, and adds a layer of requirements on top of them. It does not promise that your system is secure; it promises that the channel carrying tokens and requests will not collapse under the known attacks.

What the profile adds

  • PAR — the authorisation request is pushed to the authorisation server over a back channel, and the browser carries only a short identifier. Fewer parameters in the browser, less room for tampering.
  • mandatory PKCE, for confidential clients as well, not only public ones.
  • nonce on every authentication request, checked against the ID token.
  • request signing — the body and the critical headers carry a cryptographic signature, so any change in transit is detected.
  • sender-constrained tokens — mTLS per RFC 8705 or DPoP, not a plain bearer token.
  • exact redirect URI matching, https only, no wildcards.
  • strong client authentication — private_key_jwt or mTLS, with no shared secrets.
  • asymmetric algorithms only, alg none forbidden, and key rotation with kid.

The table shows why each control exists — as an item someone once tried to break:

ControlThe attack it blocks
PAR — pushing the authorisation request over a back channelTampering with the authorisation request parameters in the browser, including widening scope or swapping the redirect.
PKCE on every flowInterception of the authorisation code in a public client flow — mobile or a custom URI scheme.
nonce and exact redirect URI matchingA mix-up attack, redirecting a code to an attacker's endpoint, and reuse of an ID token.
Request signing (JWS)Alteration of the request body in transit — amount, beneficiary account, currency — by an intermediary or proxy.
A token bound to the certificate (mTLS) or to DPoPReuse of a stolen token from another machine, even when the token is valid.
Client authentication with private_key_jwt or mTLSImpersonation of a legitimate client at the authorisation server, and theft of a shared client secret.
Asymmetric algorithms and the ban on alg noneForging a token through a weak signature check or an algorithm swap.

Two things worth absorbing. The first: the profile does not replace authorisation checks. It handles the channel — authentication, integrity, freshness — not the question of whether client X may act on object Y. You can be compliant with the profile down to the last detail and still be vulnerable to BOLA. The second: do not implement it on your own. The OpenID Foundation conformance suite has real value, because it tests what nobody thinks to test: a redirect with a parameter, reuse of a code, a token never checked against its audience.

Idempotency, nonce and replay

A payment is an operation with a side effect. A request sent twice is not a duplicate request — it is two charges. Most of the failures I know do not come from an attacker but from the network: a timeout after the other side already accepted the instruction, and a retry that executed it again. This is where security and operational resilience meet.

Idempotency-Key

The semantics I recommend adopting: the client generates a unique key per logical operation, not per HTTP attempt. The server stores the key with a fingerprint of the request, the response code and the body, for a defined period; 24 hours is a common convention because it covers automatic retries and a manual fix within the same business day. A retry with the same key and the same body returns the stored response without performing the operation again. The same key with a different body is a conflict — 409 or 422 — because that is almost always a bug on the client side.

Two details decide whether it will work. The first: the key is stored where the side effect is created — a row in a table with a unique constraint on the client identifier and the key, not in the memory of the API gateway. A gateway with three replicas will not coordinate with itself, and two pods serving the same retry will execute it twice. The second: a concurrent request gets a clear response that lets the client wait or check status.

Signing with a timestamp and a nonce

Request signing gives integrity: a change in the body or in the path is detected. It does not give freshness. For that you add a timestamp and a single-use nonce, and sign them together with the rest of the request. The server rejects a request whose timestamp falls outside a 300-second window, and rejects a nonce it has already seen. The nonce is kept in a cache with a TTL no shorter than the window, otherwise it is forgotten exactly while it can still be used.

Why you need both: a timestamp alone allows reuse inside the window, and that is enough to send a payment instruction twice. A nonce alone requires memory that grows without bound. Together they give a signature that cannot be altered, a request that cannot be replayed, and bounded memory. The signature must cover the request body and not only the headers: over headers it protects the envelope and leaves the amount open.

A retry without a key

Here is what happens when there is no key. The client sends a payment instruction; the server executes it and gets an approval from the other side; the response is lost in transit. The client times out and tries again, and the server executes again. On a credit card this looks like two charges, on a bank account like two transfers, and in reconciliation like an orphan entry discovered two days later. The refund costs money, and detection takes time — and sometimes the customer has already paid twice before anyone notices.

The key does not promise that the request will arrive; it promises that if it arrives again, the result will be the same.

A short example, with a signature and with a key:

POST /v1/payments HTTP/1.1
Host: api.example-pay.sg
Content-Type: application/json
Idempotency-Key: 4b1f7a3e-1c2d-4f5a-9b0e-7d6c2a1f8e30
X-Request-Timestamp: 1763318400
X-Request-Nonce: 0f6a2c9e-8b71-4d33-9a55-2c1e7f0d4b18
X-Request-Signature: MEUCIQDk3nZ7...

{"amount":{"value":"149.90","currency":"SGD"},"account_id":"acc_8842"}

The first response is 201 with a payment identifier. A retry with the same key returns 200 with the same identifier, and the header Idempotent-Replayed: true. The 201 versus the 200 is not cosmetic: it tells the client whether it created something or read an existing result.

The API gateway: what goes in it and what does not

The API gateway is a good place to concentrate cross-cutting controls. It has one big advantage — a single enforcement point, a single log, a single configuration — and one big drawback: it creates a false sense of security. A good gateway stops malformed, slow or aggressive requests. It does not know who owns an account.

What does belong there:

  • rate limiting per client and per operation, with a different weight for a payment and for a balance read. A 429 response with Retry-After, and a log of who crossed the line.
  • schema validation against OpenAPI, including rejection of unknown fields, maximum lengths and closed enums.
  • size limits — request body, headers and number of fields. A 413 is a better answer than a parser crash the server did not survive.
  • JSON depth and data-type limits — maximum depth, array length, no duplicate keys. That is what separates an unusual request from the exploitation of a parser.
  • timeouts and circuit breaking per route, with bounded retries. An unbounded retry turns an internal fault into a flood.
  • token validation — signature, exp, nbf, aud, scope — and mTLS termination at the gateway, passing a signed identity inward rather than a header the client set.

And what does not belong there: object ownership checks, business velocity limits (how many transfers per hour for a new account), amount ceilings that are a function of the customer's history, and KYC status. All of these need data the gateway does not hold, so any implementation of them there ends in an exception table or a workaround.

Diagram of the API security layers in payments: a client with mTLS, an API gateway with rate limiting and validation, and a service that performs the authorisation check on the object
Three layers, three responsibilities: identity authentication in the outer layer, cross-cutting controls at the gateway, and the decision on the object in the service that holds it.

Where each control sits

The outer layer holds mTLS, client authentication and coarse rate limiting. In the middle sits the API gateway with validation, size limits and timeouts. Inside sits the service that holds the object, and it is the only one that can decide whether the caller may act on it. Any control in the wrong place is either not enforced, or enforced too late to prevent damage.

There is a pattern I like: the gateway applies coarse policy quickly, and the service applies fine-grained policy. The business decision stays in the service, with a log — who, on what, what the answer was, and why. That log is both an investigation tool and audit evidence.

If you use OPA or a similar policy engine, ask one question before writing a line of Rego: does the engine have the data it needs to decide on the object. A policy without object data is decoration. If the data comes from the service that holds it, the decision may as well be made there.

Testing

API security is measured in tests, not in documents. I look for three things: that the contract is tested, that authorisation is tested from the wrong side, and that error codes do not tell an attacker what they are trying to find out.

Contract tests

A contract test is first of all an inventory test. Every endpoint that is published must appear in the specification, and every change to the specification must pass a backward compatibility check. An OpenAPI diff in CI catches a deleted field, a narrowed enum and a parameter that became mandatory. From a security point of view, an endpoint that is not in the specification is not "one more API" — it is an endpoint with no tests and no one accountable for it.

Negative ownership tests

This is the only test I know that actually identifies BOLA. For every endpoint that accepts an identifier, run the scenario with someone else's identity — another user, another tenant, another service — and verify that the response is not the data. A matrix of identity against object is not overkill; it is the minimum. And if a new endpoint is added without such a test, the build should fail — that is the only rule I know that holds over time, because it does not depend on a person's discipline.

DAST and fuzzing

DAST tools are good at finding what patterns catch — missing headers, verbose errors, unauthorised methods. They are bad at finding authorisation problems, because those have no signature. Schema-based fuzzing makes up for that: requests of every data type, JSON depth, Unicode, null instead of an object, an array instead of a string. A property-based tool that generates requests from OpenAPI and runs them twice — once with the owner's identity and once with another — gives better coverage than any list of test cases.

Errors that do not disclose existence

The test is small and critical: the same status code, the same response structure and the same response time, whether the object does not exist or exists but does not belong to the caller. If "not found" and "no permission" look different, you have an API that maps the database for anyone who asks. The same holds for response times and response size, which is why an ownership check that runs an extra query and returns 404 only after it is faster when there is no row at all — and that difference can be measured.

Tests that cover only the happy path

A test suite that runs only with the owner's identity will pass at 100% even when the API is wide open to BOLA. That is not a failure in the tests — it is a failure in defining what is tested. If the plan does not contain a single test that runs a legitimate request with the wrong identity, you do not have an authorisation test; you have a sanity check. I recommend making it a gate in CI, not an item at the end of the to-do list.

Regulatory context

PCI DSS 4.0.1 is the current version of the standard, and it applies to APIs in two main places. The first is requirement 6.x — secure development: coding standards, code review, change management, patch management and handling of application-level attacks. The second is 11.x — security testing: vulnerability scans and penetration tests, including testing of network and application separation. The standard does not make the API secure, but it forces controls to be documented — and that starts with someone having to show an inventory.

The inventory is the practical point. The standard requires an inventory of system components and bespoke software, and every API version is such a component. If you do not know which versions are running, which endpoints are exposed to partners and which were left over from an old environment, you have nothing to test. It is also the ninth category on the OWASP list, and not by accident: the inventory is a precondition for every other control.

The Singapore framework

In Singapore, the Payment Services Act 2019 is the relevant regulatory backdrop: it regulates the activity of payment service providers and brings them under supervision. Alongside it sit the Technology Risk Management Guidelines of MAS — the Monetary Authority of Singapore, which licenses and supervises payment service providers under that Act — together with MAS Notices 644 and 655 on cyber security management and cyber hygiene; requirements from the Cyber Security Agency of Singapore under the Cybersecurity Act 2018; guidance from the ABS, the Association of Banks in Singapore; and the Personal Data Protection Act 2012 with the PDPC wherever personal data is involved. I mention them as context only: the statute itself does not spell out engineering controls, and it will not replace your threat model. What it does set is the environment of accountability in which you will have to show process, documentation and testing.

The practical meaning is simple: if you run a payments API — whether it settles over FAST and PayNow, GIRO or a card scheme — someone will ask for four things: an endpoint inventory, a description of the authorisation model, evidence of testing and change management. You can produce them only if they are part of the process, not if they are written a week before an audit.

Key takeaways

  • The API is both the product and the surface: most exposure is a missing authorisation decision on an object, not an authentication bypass.
  • BOLA is the first category in the OWASP API Top 10 and a design problem; the fix is ownership in the query or in a policy engine, not in a WAF.
  • mTLS identifies a client; OAuth 2.1 identifies a user. You need both, with a scope per operation and an audience check.
  • FAPI 2.0 hardens the channel and removes dangerous options, but it does not check whether the object is yours.
  • Idempotency, a request timestamp and a nonce are security controls: without an Idempotency-Key, a retry is a double charge.

Sources and links

  1. OWASP API Security Top 10 — 2023
  2. RFC 8705 — Mutual-TLS Client Authentication and Certificate-Bound Access Tokens
  3. RFC 8446 — TLS Protocol Version 1.3
  4. OpenID Foundation — Financial API, Part 1: Security Profile
  5. OpenID Foundation — Financial API, Part 2: Security Profile
  6. Open Policy Agent — a policy engine for authorisation decisions
  7. PCI Security Standards Council — document library, PCI DSS 4.0.1
  8. MAS — Technology Risk Management Guidelines and Notices 644 and 655