Access Control for Payment APIs
Last Updated: 2026-12-01 Status: Complete
Access control for payment APIs answers three questions on every request: who is calling (authentication), what may they do (authorization) and how do you stop abuse (rate and behavior controls). This page covers API keys, OAuth 2.0 and JWT, mTLS, role-based access control (RBAC) with tenant isolation, MFA, production and secrets access, and the OWASP risks that matter to payments. It ends with two NestJS building blocks: an API-key guard and a roles guard with tenant-scoped data access.
Requirement numbers follow PCI DSS v4.0.1 — all future-dated requirements mandatory since 31 March 2025; standards editions are tracked on Key Numbers. Confirm CDE access design with your QSA and security leadership.
Quick Reference
| Control | Rule |
|---|---|
| API keys | Store only a hash; prefix plus key id for lookup; scopes; test and live separated; rotate with overlap |
| Browser or app credentials | Publishable keys only; secret keys never leave servers |
| Platforms acting for merchants | OAuth 2.0 authorization code; client credentials for platform-owned calls |
| JWT | Verify signature, allowlist alg, check issuer, audience and expiry |
| Tenant isolation | Every query scoped by tenant (OWASP API1) |
| MFA | MFA for all non-console access into the cardholder data environment by any user, not only administrators (Req. 8.4.1 covers administrative access), mandatory since 31 March 2025 |
| Access reviews | All user accounts and their access privileges reviewed at least once every six months |
| Current OWASP lists | OWASP Top 10:2025 for web applications; OWASP API Security Top 10:2023 for APIs |
How Should You Authenticate API Callers?
Secret API Keys
A secret key is a bearer credential: whoever holds it is the account. Design for the day one leaks.
- Format. Use a recognizable structure such as
sk_live_<keyId>_<random>(shown assk_test_[redacted]in examples), with the key id and random part encoded in an alphabet that cannot contain the separator, such as hex or base32. The prefix identifies environment and type;keyIdlets you look up the record without scanning; the random part has at least 128 bits of entropy. - Store only a hash. Keep the key id, a hash of the secret, scopes, owner, creation time, last-used time and status. Show the full secret exactly once at creation. Because the secret is high-entropy random, a fast hash such as SHA-256 is acceptable; a slow password hash is not needed, but add a server-side pepper if your policy requires it.
- Scopes. A key grants named permissions (
payments:write,payouts:read), not "everything". Default to least privilege. - Test vs live. Separate key spaces, separate data, and reject a test key on live endpoints.
- Rotation with overlap. Allow two active keys per integration so customers can deploy the new key, then revoke the old one. Support an expiry date.
- Leak response. Publish a recognizable prefix so secret scanners can detect keys in public repositories, subscribe to scanning programs your code host offers, and provide one-click revoke. Alert on a key used from a new region or at an unusual rate.
- Never accept keys in URLs; use the
Authorizationheader so they stay out of access logs.
Publishable vs Secret Keys
A publishable key may appear in browser or mobile code and can only do low-risk things such as creating a token via hosted fields. It must not authorize reads of sensitive data or money movement. This split is what lets you tokenize at the edge (see Handling PII and Card Data).
OAuth 2.0 and Platforms Acting for Merchants
OAuth 2.0 (RFC 6749) fits when a third party acts for your merchant:
| Grant | Use for |
|---|---|
| Authorization code (with PKCE, now recommended for all authorization-code clients) | A software platform or partner acting on behalf of a connected merchant after that merchant consents; the token is scoped to that merchant |
| Client credentials | Server-to-server calls where the client acts as itself, such as your partner calling your reporting API |
Issue short-lived access tokens with narrow scopes and a tenant or merchant binding, keep refresh tokens encrypted and revocable, and record every grant and revocation in the audit trail. Bearer-token handling is defined in RFC 6750.
JWT Validation Pitfalls
A JWT (RFC 7519) is only trustworthy after you validate it.
- Verify the signature with a key from a trusted source (your issuer's JWKS), never from the token itself.
- Allowlist algorithms. Reject
noneand reject algorithm switching (for example accepting an HMACalgwhen you expect an asymmetric key). - Check
iss,audandexp(andnbfif used). A token for another audience is not for you. - Do not trust unvalidated claims for tenant or role decisions; look up authorization server-side where the claim could be stale.
- Keep lifetimes short and design revocation for high-risk actions.
- Use a maintained library with explicit options rather than hand-rolled parsing.
Mutual TLS for High-Value Server-to-Server Links
For a bank, processor or large partner link, add mutual TLS so the client proves possession of a private key. RFC 8705 defines OAuth 2.0 mutual-TLS client authentication and certificate-bound access tokens, which stop a stolen token from being replayed by someone without the certificate. The cost is certificate issuance, rotation and monitoring, so reserve it for links where the risk justifies it.
How Do You Authorize Requests?
RBAC for Dashboard Users
RBAC assigns permissions to roles and roles to users. A starting matrix for a merchant or platform dashboard:
| Permission | Owner | Admin | Developer | Finance | Support | Analyst |
|---|---|---|---|---|---|---|
| View payments | Yes | Yes | Yes | Yes | Yes | Yes |
| Issue refunds | Yes | Yes | No | Yes | Limited | No |
| Manage API keys | Yes | Yes | Yes | No | No | No |
| View full bank details | Yes | Yes | No | Yes | No | No |
| Change payout bank account | Yes | Yes | No | Step-up approval | No | No |
| Approve payouts | Yes | No | No | Yes | No | No |
| Manage users and roles | Yes | Yes | No | No | No | No |
| Export data | Yes | Yes | No | Yes | No | Masked only |
Treat the matrix as a policy to review, not a standard. Review user accounts and privileges on a schedule: All user accounts and their access privileges reviewed at least once every six months.
Tenant Isolation (OWASP API1 and API5)
In a multi-tenant platform the commonest serious flaw is broken object level authorization (API1): the caller changes /payments/{id} to another tenant's id and gets data. Prevent it structurally:
- Derive
tenantIdfrom the authenticated principal, never from a request parameter. - Make every repository method require a tenant argument, or use a tenant-scoped repository wrapper, so an unscoped query does not compile.
- Return 404 rather than 403 for another tenant's object, to avoid confirming it exists.
- Add Postgres row-level security as a second layer if your architecture allows.
- Check function-level access (API5): admin-only endpoints (refunds above limits, manual ledger adjustment) enforce roles server-side, not by hiding buttons.
Tenant structure is described in Entity Model.
ABAC for Fine-Grained Rules
Roles say who you are; attributes say whether this specific action is allowed. Examples: a finance user may approve payouts only up to a limit, only for tenants in their portfolio, and not payouts they initiated (separation of duties). Express these as policy functions evaluated with attributes of the actor, the resource and the context, and keep thresholds in configuration set from your own risk appetite.
Support Impersonation
Support often needs to see what a merchant sees. Do it safely: separate session type, explicit reason and ticket reference, time-boxed, read-only by default, sensitive reveals still step-up gated, a visible banner, and every action audited with the agent as actor and the merchant user as on_behalf_of (see Audit Trails).
How Should MFA Work?
MFA is required for non-console access into the CDE (MFA for all non-console access into the cardholder data environment by any user, not only administrators (Req. 8.4.1 covers administrative access), mandatory since 31 March 2025). Requirement 8.4.1 covers administrators specifically, and 8.4.2 extends MFA to all users. Requirement 8.4.3 adds MFA for remote network access from outside your network. Apply it to all dashboard users in practice.
- Prefer phishing-resistant factors: WebAuthn and passkeys. NIST guidance: NIST SP 800-63B-4, final July 2025; SMS and voice one-time codes are a restricted authenticator. SMS and voice codes are weaker; offer them only as a fallback if your risk assessment allows.
- Step-up MFA for sensitive actions. Even in a valid session, require a fresh factor to change the payout bank account, create or rotate API keys, change MFA settings, approve a large payout or reveal full bank details.
- Notify and delay. After a payout-destination change, notify existing contacts and consider a hold before the first payout to the new destination.
- Recovery is an attack surface. MFA reset flows need stronger proof than login and must be audited.
How Should You Control Production Access?
Developers and operators are privileged users too.
| Practice | Detail |
|---|---|
| Least privilege | Access by job function (Req 7.2); no standing admin |
| Just-in-time access | Request, approval by a second person, scoped role, automatic expiry |
| Break-glass | Emergency account with sealed credentials, alarm on use, mandatory review afterward |
| Session logging | Record administrative sessions and commands; administrative actions are Req 10.2.1.2 events |
| Safer debugging | Masked read replicas, synthetic data or tokenized snapshots; never copy production PII or card data to lower environments |
| Review | Periodic access reviews and removal at role change or departure |
How Do You Manage Secrets?
Secrets management means credentials live in a managed store, are delivered at runtime and can be rotated without a code change.
- No hardcoded credentials. Requirement 8.6.2 prohibits hardcoded passwords in scripts, configuration files and custom code for system and application accounts. Run secret scanning in CI and on repositories.
- Use a vault or managed secret store with per-service identities, so a service reads only its secrets.
- Prefer dynamic, short-lived credentials. HashiCorp Vault documents dynamic secrets with a lease and TTL, revoked automatically when the lease expires; a leaked database credential then dies on its own.
- Rotate on a schedule set by risk analysis (Req 8.6.3) and immediately on suspected compromise.
- Webhook signing secrets are per endpoint, rotated with an overlap window; see Webhooks.
- Keys for encryption stay in KMS or an HSM; services call the KMS rather than holding key material.
- Keep secrets out of logs, error messages, images and CI output.
How Do You Defend Against Abuse?
Rate Limiting
Rate limiting protects availability and money. Limit per API key, per source IP and per account or merchant, with separate, stricter limits on sensitive operations (login, MFA, token creation, payment attempts). Return HTTP 429 (defined in RFC 6585) with a Retry-After header (RFC 9110) and document the limits. Set numbers from your own baselines and load tests, not from copied examples. This addresses OWASP API4 (unrestricted resource consumption).
Card-Testing Defenses
Fraudsters use payment endpoints to validate stolen cards. Layer velocity limits per IP, device and token, CAPTCHA or challenge on public forms, minimum amount and decline-rate monitoring, and automatic blocking. Patterns and thresholds are in Fraud Patterns and Fraud Detection Tools. This is OWASP API6 (unrestricted access to sensitive business flows).
DDoS and Edge Protection
Put a CDN or WAF in front of public endpoints to absorb volumetric attacks, filter known bad traffic and terminate TLS, and keep origin addresses private. Design for graceful degradation: payment creation survives when reporting is shed.
Headers and Payment-Page Script Controls
- Send
Strict-Transport-Security(HSTS), a restrictiveContent-Security-Policy,X-Content-Type-OptionsandReferrer-Policy. - If you host any payment page, Requirement 6.4.3 requires scripts to be inventoried, authorized and integrity-checked, and Requirement 11.6.1 requires change- and tamper-detection on payment-page HTTP headers and scripts as received by the browser. Both are future-dated requirements that became mandatory with PCI DSS v4.0.1 — all future-dated requirements mandatory since 31 March 2025. A hosted-fields approach shrinks, but does not remove, your responsibility for the page that embeds them; ask your QSA.
Vulnerability Management and the OWASP Lists
Use the current lists (OWASP Top 10:2025 for web applications; OWASP API Security Top 10:2023 for APIs) as design and review checklists. For payment APIs these API Security Top 10 items matter most:
| OWASP API risk | Payment example | Mitigation |
|---|---|---|
| API1 Broken Object Level Authorization | Reading another merchant's payment by id | Tenant-scoped queries |
| API2 Broken Authentication | Weak key handling, unvalidated JWT | Hashed keys, strict JWT checks, MFA |
| API3 Broken Object Property Level Authorization | Response leaks bank details or internal risk score; mass assignment of fee_plan | Response DTO allowlists, validated input DTOs |
| API4 Unrestricted Resource Consumption | Unbounded exports, expensive reports | Rate limits, pagination caps |
| API5 Broken Function Level Authorization | Developer role calls refund-all | Role guards on every handler |
| API6 Unrestricted Access to Sensitive Business Flows | Card testing, promo or payout abuse | Velocity controls, friction |
| API7 Server Side Request Forgery | Webhook URL pointing at internal metadata services | Validate and resolve URLs, egress allowlist |
| API8 Security Misconfiguration | Verbose errors, open storage | Hardened defaults, config review |
| API9 Improper Inventory Management | Forgotten v1 endpoint without checks | API inventory, retire old versions |
| API10 Unsafe Consumption of APIs | Trusting a partner response blindly | Validate upstream data, timeouts |
Also run dependency scanning and patching (software supply chain), and tests and scans on the schedule your QSA and policy require. See PCI DSS Requirements.
NestJS Example: An API-Key Guard
@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(
@InjectRepository(ApiKeyEntity) private readonly keys: Repository<ApiKeyEntity>,
@Inject(API_MODE) private readonly mode: 'live' | 'test', // environment this deployment serves
) {}
async canActivate(ctx: ExecutionContext): Promise<boolean> {
const req = ctx.switchToHttp().getRequest();
const header: string | undefined = req.headers['authorization'];
const presented = header?.startsWith('Bearer ') ? header.slice(7) : undefined;
if (!presented) throw new UnauthorizedException();
// Format: sk_<mode>_<keyId>_<secret>, where keyId and secret are hex or base32
// (no underscores). Reject anything else without logging the value.
const parts = presented.split('_');
if (parts.length !== 4 || parts[0] !== 'sk') throw new UnauthorizedException();
const [, mode, keyId, secret] = parts;
const record = keyId ? await this.keys.findOne({ where: { keyId, mode, revokedAt: IsNull() } }) : null;
const presentedHash = createHash('sha256').update(secret ?? '').digest();
const storedHash = record?.secretHash ?? Buffer.alloc(32); // constant-time comparison of the secret hash
const ok = timingSafeEqual(presentedHash, storedHash);
// reject unknown, wrong, expired, and test keys presented to the live environment
if (!record || !ok || isExpired(record) || record.mode !== this.mode) throw new UnauthorizedException();
// generic error for every case; record the failure in the audit trail separately
req.user = { type: 'api_key', id: record.keyId, scopes: record.scopes }; // same property the JWT path sets
req.tenantId = record.tenantId; // tenant comes from the key, never from the request
return true;
}
}
The guard never logs the presented key, returns the same error for unknown and wrong keys, and sets the tenant from the stored record.
NestJS Example: Roles and Tenant-Scoped Access
export enum Role { Owner = 'owner', Admin = 'admin', Developer = 'developer',
Finance = 'finance', Support = 'support', Analyst = 'analyst' }
export const Roles = (...roles: Role[]) => SetMetadata('roles', roles);
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(ctx: ExecutionContext): boolean {
const required = this.reflector.getAllAndOverride<Role[]>('roles', [ctx.getHandler(), ctx.getClass()]);
if (!required?.length) return false; // deny by default: every handler must declare roles
const { user } = ctx.switchToHttp().getRequest();
return required.some((r) => user?.roles?.includes(r));
}
}
@Injectable()
export class TenantPaymentRepository {
constructor(@InjectRepository(Payment) private readonly repo: Repository<Payment>) {}
findOne(tenantId: string, id: string): Promise<Payment | null> {
return this.repo.findOne({ where: { tenantId, id } }); // no method exists without tenantId
}
}
@Controller('payments')
@UseGuards(JwtAuthGuard, RolesGuard)
export class PaymentsController {
constructor(private readonly payments: TenantPaymentRepository) {}
@Get(':id')
@Roles(Role.Owner, Role.Admin, Role.Finance, Role.Support, Role.Analyst, Role.Developer)
async get(@Req() req, @Param('id') id: string) {
const payment = await this.payments.findOne(req.tenantId, id);
if (!payment) throw new NotFoundException(); // 404 for other tenants' ids too
return PaymentResponseDto.from(payment); // allowlisted fields only (API3)
}
}
Attribute rules (payout limits, separation of duties) go in a service called after the role check, and step-up requirements in a dedicated guard that checks the session's last MFA time.
Common Mistakes
- Storing API keys in plaintext "so support can show them"
- Reading
tenantIdfrom the request body or path - Hiding admin buttons in the UI but not checking roles on the endpoint
- Accepting any JWT algorithm or skipping the audience check
- No expiry or overlap on keys, so rotation causes an outage and never happens
- Standing production admin access with no approval or expiry
- Rate limiting by IP only, which fails behind shared NATs and is evaded by botnets
- Allowing webhook URLs that resolve to internal addresses
Related Topics
- Audit Trails: recording every grant, impersonation and sensitive read
- Handling PII and Card Data: what the access controls protect
- Payments API Design: errors, versioning and resource design
- Webhooks: signing secrets and receiving endpoints
- PCI DSS Requirements: Requirements 6, 7, 8 and 11 in context
- Check your understanding: Security Quiz
References
- PCI DSS v4.0.1 and supporting documents: PCI Security Standards Council (Requirements 6.4.3, 7.2, 8.3 to 8.6, 11.6.1)
- RFC 6749: The OAuth 2.0 Authorization Framework: IETF, 2012
- RFC 6750: The OAuth 2.0 Bearer Token Usage: IETF, 2012
- RFC 8705: OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens: IETF, 2020
- RFC 7519: JSON Web Token (JWT): IETF, 2015
- RFC 6585: Additional HTTP Status Codes: IETF, 2012
- RFC 9110: HTTP Semantics: IETF, 2022
- OWASP Top 10:2025: OWASP Foundation, 2025
- OWASP API Security Top 10:2023: OWASP Foundation, 2023
- NIST SP 800-63B-4: Authentication and Authenticator Management: NIST, July 2025
- Vault lease documentation: HashiCorp (vendor)