Secure API integrations by checking caller identity, enforcing tenant permissions, validating data, and limiting usage. Use the OWASP API Security Top 10-2023 as a risk framework, not a certification.
The process covers 4 steps:
- Control access: Check tokens and enforce object, field, and function permissions on every request.
- Check data and usage: Apply schemas, quotas, workflow limits, and idempotency keys to prevent duplicate writes.
- Secure connections and changes: Restrict outbound requests, validate partner responses, and track API versions and secrets.
- Test before release: Block deployment when critical controls fail, then monitor security events and assign response owners.
Start by mapping APIs, data flows, and owners. Require passing security tests and recorded approval before deployment.
Secure API Integrations: 4-Step OWASP Workflow
OWASP API Security Top 10 Course – Secure Your Web Apps
sbb-itb-01010c0
Step 1: Verify Identity and Enforce Tenant Access
With scope defined, control who can call each API and what they can do. Authentication verifies the caller; authorization limits its actions. Enforce both at the object, property, and function levels. These checks establish tenant isolation and least-privilege access, blocking updates without permission and privilege escalation in partner integrations. A valid token alone never grants broad access.[3][5]
Configure HTTPS, Credentials, and Token Checks
Require HTTPS with modern TLS on every endpoint. Reject plaintext HTTP, and assign separate identities to each partner, application, and environment.
Use short-lived access tokens with narrow scopes. For JWTs, verify the signature against the issuer’s approved key set. Allow only explicitly configured algorithms, and reject algorithm changes and unsigned tokens. Validate issuer (iss), audience (aud), expiration (exp), not-before (nbf), and required client or tenant claims.[4][6]
For opaque tokens, use the provider’s supported validation method to check active status, issuer, audience, expiry, client identity, tenant context, and scopes. Enforce scopes separately after validation. Never log complete tokens.
Choose a client authentication method based on the partner’s risk and ability to manage certificates.
Choose Partner Authentication Methods
Use OAuth 2.0 client credentials when an application acts on its own behalf.
| Method | Deployment fit | Complexity | Credential risk | B2B use case |
|---|---|---|---|---|
| OAuth 2.0 bearer access tokens | Broad compatibility with managed identity providers and standard API gateways | Low to medium | A stolen, unexpired token can be replayed. | General partner APIs and application-only integrations |
| Mutual TLS (mTLS) | Both parties can manage certificates and enforce TLS client authentication | Medium to high | Requires private-key protection and certificate lifecycle management; certificate-bound tokens reduce replay risk | High-value financial, healthcare, supply-chain, or regulated integrations |
| Signed client assertions | Partner can protect a signing key; token endpoint supports JWT client authentication | Medium | An exposed private key enables forged assertions until rotation or revocation | Server-to-server OAuth authentication without a reusable client secret |
Signed client assertions authenticate clients at the token endpoint. mTLS can authenticate clients and, where supported, bind access tokens to client certificates. If stolen-token replay poses unacceptable risk, consider certificate-bound tokens or DPoP sender constraints.
After authentication, check tenant, object, field, and function permissions on every request.
Check Object, Field, and Function Permissions
Derive tenant identity from validated authentication context or a server-side client mapping, never from an untrusted tenant_id in the request. For partners serving multiple tenants, check the selected tenant against the client’s permitted tenant set.
Deny access by default to objects, readable and writable fields, and privileged functions. Use tenant-filtered queries and transaction-safe updates, including on alternate endpoints.[3][5]
Example: invoice authorization flow
request: authenticated_tenant = trusted_auth_context.tenant_id action = request.operation invoice_id = request.path.invoice_id invoice = load_invoice(invoice_id) if invoice is missing: deny with a non-disclosing not-found response if invoice.tenant_id != authenticated_tenant: deny with a non-disclosing not-found response record a cross-tenant authorization event if action == "read": require scope "invoices:read" return only fields allowed for this client and tenant if action == "update": require scope "invoices:write" allow only fields in ["due_date", "reference", "payment_status"] reject ["tenant_id", "total_amount", "approval_history", "risk_score"] if action == "approve": require scope "invoices:approve" require an approved role or policy for the authenticated client require invoice.status == "pending" perform the state change server-side otherwise: deny because the function is not explicitly allowedTest that permitted same-tenant reads succeed, substituted cross-tenant invoice IDs return a non-disclosing response, changes to
tenant_idortotal_amountfail, and billing clients cannot approve invoices. Record denials without exposing tokens or sensitive invoice data.[3][5]
Step 2: Validate Data and Limit API Use
Use schema validation, resource limits, and workflow controls to block malformed input, automated abuse, and duplicate execution.
Enforce Request and Response Schemas
Validate every endpoint against an explicit server-side schema before business logic runs. Check request bodies, path and query parameters, headers, and content type. Enforce types, lengths, numeric ranges, formats, allowed values, array sizes, and nesting depth.
Reject unknown writable fields. Map approved inputs explicitly rather than binding request objects directly to database models.
Define response schemas separately from internal models. Before serialization, apply field-level authorization for each role and tenant, including nested objects. Schemas don't replace authorization or injection defenses. Keep parameterized queries and safe output encoding in place.
Set Resource Limits and Workflow Controls
Once the request passes schema validation, limit how often each integration can run and how much it can consume.
Enforce payload and upload limits at the gateway. In the application and infrastructure, set limits for pagination, query complexity, execution time, concurrency, and queued jobs. Also limit failed requests, retries, and downstream calls.
Apply burst throttling and longer-term quotas by client, tenant, endpoint, and business action. Give expensive operations a higher quota weight. When throttling, return 429 Too Many Requests with a safe Retry-After value.
For sensitive workflows, add transaction ceilings, cooldowns, approval steps, and anomaly checks. An authorized action can still cause harm when repeated at scale. Apply workflow controls alongside provider spending limits or billing alerts for third-party services.
Prevent duplicate side effects from write actions by requiring idempotency keys for non-idempotent actions. Scope each key to the authenticated tenant, client, and operation, and bind it to a normalized request hash.
Atomically reserve the key before execution, then store its status and results for a fixed retention period. Reject changed payloads with 409 Conflict. Concurrent duplicates must not execute twice; return the stored result or a conflict.
| Control | Risk addressed | Enforcement point | Verification evidence |
|---|---|---|---|
| Schema and field validation | API3 property tampering and exposure | Request validation, write mapping, response serialization | Field rejections; denied reads and writes |
| Payload and upload limits | API4 parser, memory, and storage exhaustion | Gateway and application | Size rejections; CPU and memory use |
| Rate limits | API4 bursts; API6 automated actions | Client-, tenant-, endpoint-, and action-level throttles | Request counts; 429 rates; recovery time |
| Quotas and spending limits | API4 sustained consumption and provider costs | Application counters and provider controls | Quota use; provider calls; cost alerts |
| Pagination and query bounds | API4 expensive reads | Query layer and database timeouts | Rows scanned; response size; query duration |
| Idempotency | Duplicate business side effects | Atomic operation record | Suppressed duplicates; hash conflicts; concurrency outcomes |
| Workflow controls | API6 harmful repetition | Business logic and approval policies | Action velocity; blocks; manual-review rate |
Step 3: Secure Connections and Manage API Changes
Harden Settings and Outbound Requests
After input validation and rate limits, tighten outbound calls and change controls. Disable unused HTTP methods, routes, debug endpoints, test accounts, default credentials, directory listings, and verbose error responses. Return generic errors to clients and send detailed diagnostics only to protected logs.
Restrict admin endpoints to private networks or a separate management plane. Require strong authentication and authorization. Limit CORS to approved browser origins; CORS is not API authentication.
For API7:2023 Server Side Request Forgery, secure outbound partner callbacks, webhooks, and service-to-service requests. Use fixed partner destinations where possible. Otherwise, allow only approved hostnames, schemes, ports, and paths.
Resolve the hostname once, validate the IP, and connect without a second DNS lookup. Keep the hostname for certificate validation. Disable redirects or repeat these checks at every hop, retry, and fallback. Add egress rules to block restricted internal networks and cloud metadata services.
Validate Partner Data and Handle Failures
Treat partner responses as untrusted under API10:2023. A partner failure must not corrupt data or trigger duplicate execution. Before processing responses, enforce schemas, content types, encoding, and size limits. Verify HTTPS certificates and hostnames. Give each partner separate least-privilege credentials, and never fetch URLs from partner data without validation.
Set connection, TLS handshake, read, total-request, and response-size limits based on the partner’s expected service levels. Retry only transient failures, such as selected 408, 429, and 5xx responses. Use exponential backoff with randomized jitter, cap attempts and total elapsed time, and honor server-provided retry guidance. Require an idempotency key before retrying write calls.
Test malformed, oversized, slow, redirected, and failed responses, along with invalid certificates, DNS changes, repeated 429s, and partial transaction failures. Confirm that failures fail closed, release resources, and do not leak credentials or internal details. Record retry counts and exhausted retries as security and reliability events.
Manage Versions, Secrets, and Environments
Once partner calls are stable, track every version and environment that can expose them. Address API9:2023 Improper Inventory Management by recording each endpoint’s owner, support period, version, environment, and dependencies. This helps prevent shadow routes and broken integrations during partner updates.
Compare specs with gateway config, service discovery, load balancers, repos, and traffic to find undocumented or shadow endpoints. Scan for debug routes, old versions, alternate hostnames, and test deployments.
Before retiring an endpoint, publish the migration timeline and communicate requirements to partners. Remove routing and deployment artifacts, revoke associated credentials, and remove obsolete documentation and DNS records. Verify through both authenticated and unauthenticated requests that old routes no longer resolve.
Patch dependencies and store secrets in a secrets manager. Keep production credentials and data out of development, testing, and staging environments. Define emergency revocation procedures for keys and certificates, then verify that revoked credentials fail immediately.
Apply these controls as release gates before security testing and deployment.
Step 4: Test Controls and Approve Deployment
Verify the identity, schema, rate-limit, and partner controls implemented in Steps 1–3.
Run Security Tests Before Release
Run release-blocking tests in preproduction before every production release. Map each failure to the OWASP API Security Top 10. Unresolved critical control failures must block deployment. Track lower-risk findings in a dated remediation plan.[2][7]
| Control | Test procedure | Expected result | Evidence | Review frequency |
|---|---|---|---|---|
| Object, field, function, and tenant permissions | Attempt cross-tenant reads, restricted field changes, and function calls without permission. | No data access or actions without permission. | Permission test results | Every release |
| Token validation | Submit expired tokens, invalid signatures, and tokens missing required claims. | Every invalid token is rejected. | Authentication test report | Every release |
| Schemas and resource limits | Submit malformed and oversized inputs; exceed request and concurrency limits. | Invalid input is rejected; limits hold. | Schema results and load metrics | Every release |
| SSRF and partner connections | Attempt blocked destinations and confirm that approved partner endpoints succeed only after validation. | Blocked destinations are rejected; partner access proceeds only after validation. | Egress logs and integration results | Every release and after partner onboarding |
Treat failed release-blocking tests as deployment blockers. Keep approved results as deployment evidence.
Monitor Security Events and Review Changes
Use test results and live telemetry to spot regressions after release. Record authentication failures, access denials, and validation failures in JSON logs that support alerts and investigations. Mask secrets and unnecessary sensitive data.[2][7]
Assign named owners for security checks, alert triage, incident response, and rollback. Set alerts for unusual traffic, cross-tenant access attempts, token misuse, and unexpected destinations. Give responders a clear escalation path. Reassess controls after API changes, partner onboarding, dependency changes, and incidents.[2]
Conclusion: Confirm Security Readiness
Sign-off requires passing token and tenant-permission tests, enforced schemas, tested resource limits, validated partner connections, actionable logs, and named lifecycle owners. Before deployment, engineering, security, and business owners must record approval with linked evidence, remaining risks, and the next review date.[2][7]
FAQs
Which API security fixes should I prioritize first?
Start with strong authentication and authorization. Replace basic credentials with OAuth 2.1 or OpenID Connect, and enforce TLS 1.3 or higher to protect data in transit [1].
Add rate limiting to protect backend resources from abuse, and use schema validation to help prevent injection attacks. Set up centralized logging and auditing to monitor API health and detect threats early [2][1].
Which security checks belong in my API gateway?
Use your API gateway as the primary enforcement point for real-time security policies. Apply OAuth 2.1 for authorization or OIDC for authentication, with mTLS to verify machine-to-machine identities.
Enforce rate limits, manage CORS, and allow traffic only from trusted IP addresses. Configure SSL/TLS termination and validate request schemas to reject malformed requests. Log access to maintain audit trails, and use request/response transformations to standardize formats or add security headers.
How do I set safe limits for each partner?
Set rate limits in your API gateway based on each partner’s subscription level or role in your operations. Use OAuth 2.0 scopes to limit access to the data and actions each partner needs. Consider attribute-based access control (ABAC) for context-based permissions and IP allowlisting for trusted networks.
Store policy logic in source control to track versions and support audits. Run automated simulations to test limits before deploying them to production.