Skip to content
api security best practicesAPI penetration testingMSSP security

10 API Security Best Practices for Penetration Testers

10 API Security Best Practices for Penetration Testers

In 2024, 37% of surveyed organizations reported an API security incident in the preceding twelve months, compared with 17% in 2023, and 95% had encountered security problems in production APIs. Effective API security begins with discovering the complete attack surface and testing authorization against real business rules, because scanners alone can't reliably identify BOLA, BFLA, or other logic flaws.

The API attack surface rarely matches the documentation. A dashboard may list a handful of REST services while staging endpoints, deprecated versions, GraphQL resolvers, mobile-only routes, and partner integrations remain reachable. Penetration testers have to establish what exists before they can say what's secure.

These figures come from a survey of 250 IT and security professionals, not a census of organizations, but they underline why API security needs ongoing operational attention rather than a one-time pre-release review (Salt Security's 2024 API security findings). The practices below follow a penetration-testing delivery lifecycle, from discovery and access-control testing through abuse validation, evidence, and regression testing. They also show where MSSPs can automate repeatable checks without substituting tools for expert-led business-logic analysis. For a complementary implementation perspective, see this guide for Expo developers.

Table of Contents

1. Maintain a Complete API Inventory and Discover Shadow and Zombie APIs

A tester can't assess an endpoint they don't know exists. Begin with passive discovery: inspect JavaScript bundles, mobile app traffic, DNS records, certificate transparency logs, and API gateway configurations. Then enumerate hosts, paths, and versions, including routes such as /v1/, /v2/, and /beta/, and reconcile the results against the client's OpenAPI or Swagger specification.

Undocumented routes and deprecated versions deserve close attention. A legacy endpoint may still handle production data even after the main service has moved on, while a staging host can expose functionality that never received the same review as its production counterpart. Keep examples grounded in evidence gathered for the engagement rather than assuming a familiar breach pattern proves a vulnerability in the client's environment.

Turn discovery into a testable baseline

Confirm in writing whether staging, QA, partner, and deprecated systems are in scope before probing them. Record each discovered route, host, version, authentication method, owner, and known data sensitivity; flag mismatches with official documentation for manual review.

Practical rule: An endpoint that appears obsolete isn't safe to test or ignore until the client confirms its status and scope.

For MSSPs, automated reconnaissance can help find and organize candidate endpoints across web and cloud targets, while a tester verifies whether each route is live and relevant. ThreatExploit AI's API security testing workflow can support discovery and package an inventory for review. Retain that inventory as a baseline, so a later assessment can verify that shadow or zombie endpoints were retired rather than merely removed from documentation.

2. Test for Broken Object Level Authorization (BOLA)

BOLA occurs when an API accepts a caller-supplied object identifier but doesn't check whether that caller may access the referenced object. A request such as /api/invoices/10452 may authenticate successfully while still allowing one tenant's user to view or alter another tenant's invoice. OWASP ranks BOLA as API1:2023, and its guidance emphasizes that identifiers supplied by clients require server-side permission checks (OWASP's BOLA testing guidance).

Use two identities with different ownership or tenant scopes. Capture an authorized request, substitute an object identifier belonging to the other identity, and replay it. Repeat across identifiers in URL paths, nested JSON fields, GraphQL IDs, and batch parameters.

Prove the boundary, not just the response code

Test read, create, update, delete, export, and administrative operations. A route may block unauthorized reads but allow writes, or return a generic status while still leaking sensitive fields in the response. Seed distinct, recognizable test data so the affected object is clear, and use a dedicated test tenant for write operations whenever possible.

A confirmed cross-account access path is strong evidence, but keep the proof narrow. Preserve the original request, the modified identifier, the identity context, the response, and the object state; redact personal data before it enters screenshots or reports. Evidence capture is most useful when it lets the client reproduce the exact authorization failure without exposing unrelated records.

3. Test Function-Level Authorization (BFLA) and Role Boundaries

BFLA is a vertical privilege problem: a user can reach a function their role shouldn't be allowed to use. The interface might hide an administrative action, but that says nothing about whether the API enforces the same boundary. A standard user who can call a user-export route or alter a role through a direct request has crossed a meaningful security boundary.

Build a role-permission matrix from the documented API, product behavior, and routes discovered during reconnaissance. Then replay each relevant function with lower-privileged credentials and, where safe and authorized, without credentials. Include method switching and alternate paths, because access control can be inconsistently applied across handlers.

Test the server's decision, not the user interface's menu.

Compare REST routes with any equivalent GraphQL operations. A restriction enforced in one interface can be absent in another, and a route may authorize GET while failing to protect a corresponding write method. Hidden routes found in frontend code are useful test candidates, but their presence alone isn't proof of a flaw.

For operations that change roles, export records, or modify tenant configuration, use a sandbox or test tenant whenever available. Capture the low-privilege identity, requested function, response, and resulting state. A reproducible privilege-boundary failure gives developers a clearer remediation target than a screenshot showing only that a hidden button exists.

4. Validate Authentication, Token Handling, and OAuth 2.0 Flows

Authentication testing should follow a credential through its lifecycle, not stop after confirming that a valid token works. Test session creation, expiration, refresh, logout, rotation, and revocation. Replay requests with no token, malformed or expired tokens, revoked tokens, and tokens issued for a different audience, tenant, or privilege context; then verify that access ends when the credential should no longer be accepted.

For JWTs, inspect signature verification and the issuer, audience, expiry, and key identifier claims before attempting controlled tampering. For OAuth flows, examine redirect URI validation, state handling, PKCE enforcement, and scope boundaries. A valid identity token isn't authorization: the server must still decide whether that identity can access the requested object, property, or function.

Verify the full credential lifecycle

A practical test should also cover logout and password-change behavior. If a token continues to access protected resources after the application reports that a session was revoked, record the token state, target endpoint, response, and timing of the replay. Test refresh-token rotation by checking whether an older refresh token remains usable after renewal.

Credential storage belongs in the same assessment. A 2024 survey of more than 5,600 developers and API professionals found that 27% of respondents didn't use API-key vault security tools; among organizations that did, AWS Key Management Service was used by 28% and Azure Key Vault by 24% (Postman's 2024 State of the API report). Look for exposed keys in repositories, documentation, client bundles, logs, and error responses. Centralized secrets management, access controls, rotation, and audit logging reduce dependence on developers remembering to remove credentials manually.

For a practical reference on credential handling, see API key setup for embedded wallets, and review this API key management guidance. Store decoded tokens and server responses as controlled assessment evidence, never as reusable credentials in a general report attachment.

5. Test for Excessive Data Exposure and Mass Assignment

An API response can disclose more than the interface shows, and an update endpoint can accept more than the user is meant to change. These are distinct failure modes. Excessive data exposure returns unnecessary fields; mass assignment occurs when client-supplied properties bind to internal model attributes without adequate authorization or validation.

Compare the API response with the fields the client needs to display. Look for internal identifiers, personal data, role information, tokens, or other fields that aren't required for the operation. Then add plausible but undocumented properties to create and update requests, such as role, isAdmin, price, balance, or owner_id. Read the object back to determine whether the server persisted a field the caller shouldn't control.

Keep proof minimal and specific

A changed response isn't automatically a vulnerability. Verify that the field is sensitive or security-relevant, and establish whether the caller could affect a protected state. Use a test account and redact personal information in evidence, following the client's data-handling agreement.

OWASP's API Security Top 10 includes Broken Object Property Level Authorization, a category that captures authorization failures around specific data properties as well as excessive exposure. Its broader taxonomy also identifies risks such as unrestricted resource consumption, security misconfiguration, and unsafe API consumption (OWASP API Security Top 10). That shared vocabulary can help teams connect field-level findings to the same threat model used for object and function checks.

For hands-on coverage of REST requests and response behavior, consult REST API testing guidance. Keep compliance references tied to the actual data and control affected, rather than treating a mapping as a substitute for technical verification.

6. Assess Rate Limiting and Unrestricted Resource Consumption

A rate limit should protect more than the main API route. Login, password reset, OTP, search, export, upload, and other costly operations may each create different abuse paths. In a penetration test, send controlled bursts only after agreeing request budgets and test windows with the client. Uncoordinated load testing can affect production availability or trigger real messages and cloud spend.

Check limits by identity, IP address, and token. A gateway that counts requests only by IP may be bypassed by distributed clients; a control tied only to a token may fail before authentication. Test pagination caps, unusually large payloads, and operations that trigger expensive downstream work, but stop when agreed thresholds are reached.

Separate control validation from stress testing

Observe whether limits apply consistently across API versions and whether rejection behavior is clear enough for clients to handle. Headers such as Retry-After and X-RateLimit-Remaining can help reveal policy behavior, but the decisive question is whether the server restricts the risky operation.

SMS or email workflows deserve special care. If a test could send real messages or create chargeable activity, use a sandbox or obtain explicit authorization for a tightly bounded test. Capture the request pattern, identity context, throttling behavior, and any resulting side effect. Scheduled regression assessments can then help identify whether a release weakened a previously verified control without repeating an uncontrolled burst against production. For market-data APIs, the provider's API call limits documentation illustrates why clients and testers need to understand service-specific limits before testing.

7. Test Input Validation, Injection, and Server-Side Request Forgery

Input validation is not just a form-field check. API parameters can reach databases, operating-system commands, template engines, XML parsers, or downstream services. Testers should examine JSON fields, headers, query parameters, file names, sort expressions, and filters, including values developers might assume are internal or harmless.

Use the OpenAPI specification to identify missing or permissive type, length, and format constraints, then verify behavior with controlled inputs. Probe SQL or NoSQL injection, command injection, template injection, and XML external entity handling where the technology and scope make them relevant. Pay particular attention to sort, filter, and order parameters, which may be composed into queries outside the main request-body validation path.

Treat outbound requests as a separate boundary

SSRF arises when an API fetches a user-supplied URL, for example for a webhook, image import, or document preview. Confirm outbound requests through an approved test method, such as an out-of-band callback service, rather than trying to access internal systems without authorization. Cloud metadata endpoints are sensitive; any test involving them requires explicit scope and careful handling.

If testing exposes credentials or secrets, report the exposure without storing them unnecessarily. Baseline tools can help identify common injection patterns, but manual review is still needed to understand business context and verify impact. A tool may flag a suspicious parameter without proving that the application executes it in a dangerous way. Preserve the exact request, safe proof of behavior, and remediation guidance so developers can reproduce the issue without receiving a destructive payload.

8. Assess GraphQL-Specific Risks

GraphQL's flexible query model changes how testers reason about coverage. One endpoint can expose many resolvers, nested fields, and mutations, so a protected top-level operation doesn't prove that every nested field is protected. Test schema access while authenticated and unauthenticated, and compare what different roles can discover and invoke.

If introspection is enabled, determine whether the exposed schema reveals sensitive operations or fields that should be restricted. Then assess query depth and complexity limits, batching, aliases, and field-level authorization. A single HTTP request may contain multiple operations, so request-level throttling can miss abuse when policy doesn't account for the work inside the query.

A GraphQL endpoint is one route, but it can still represent many authorization decisions.

Use role-specific identities to test each resolver and nested resource. For example, a user permitted to view a project may still be prohibited from seeing billing details nested under that project. Test that boundary directly rather than assuming parent-level access applies to every field. Likewise, determine whether batched login mutations are counted per operation or only per HTTP request, using a bounded test approved by the client.

Schema import and generated test cases can speed repetitive coverage across large APIs. They won't determine whether a business workflow should permit a particular role or tenant to access a field. Keep that judgment with the tester, and document the schema element, identity, query, response, and expected policy for each confirmed issue.

9. Verify Security Misconfiguration in CORS, Headers, TLS, and Debug Exposure

Configuration findings often sit between application code and infrastructure. Review CORS behavior by sending a controlled Origin header and checking whether the server reflects it, especially when credentials are also allowed. Verify TLS configuration and relevant security headers, then inspect errors for stack traces, internal paths, service names, or sensitive values.

Probe common documentation and diagnostic routes, such as /swagger, /v2/api-docs, /actuator, /debug, and /.env, only when they're in scope. An exposed route isn't necessarily exploitable, so inspect what it reveals and whether it changes system state. Check cloud storage or backend permissions only when the engagement explicitly authorizes those assets.

Tie the finding to reachable impact

A verbose error may expose implementation details without giving access to protected data. A permissive CORS response may be dangerous only under particular browser and credential conditions. Report the conditions clearly, including the request origin, response headers, authentication state, and accessible information.

Configuration checks are often easy to repeat, making them useful for MSSP automation and compliance evidence. ThreatExploit AI can combine configuration testing with compliance mapping, but testers should validate each finding against the service's actual deployment and policy. A control reference helps route remediation; it doesn't prove exploitability or replace a clear technical explanation.

10. Test Unsafe Consumption of Third-Party APIs

An API may enforce its own input rules and still trust upstream data too readily. Payment processors, identity providers, messaging services, and partner APIs can return malformed, oversized, unexpected, or unauthenticated data. The consuming service should validate those responses before they influence internal decisions or reach databases and downstream clients.

Start by documenting dependencies and confirming in writing which integrations are in scope. For an authorized test integration, simulate unexpected but valid responses and observe whether the target validates content type, size, structure, and redirect behavior. Check whether outbound requests include credentials that shouldn't be sent to a redirected or unrelated destination.

Verify webhook trust and replay handling

Webhook endpoints should verify cryptographic signatures and reject replayed events using appropriate freshness controls, such as timestamps or nonces. Test in a sandbox or test account so a forged or repeated event can't trigger a real payment, account change, or customer notification.

When a partner service is outside scope, don't probe it directly. Focus on how the client handles the response and report the finding to the appropriate integration or vendor-management owner. Preserve the simulated input, the target's resulting behavior, and the expected validation rule. That evidence lets the client distinguish a defect in its own integration from a concern that must be addressed with its provider.

A digital illustration showing a server rack with an API settings window featuring a misaligned security switch.

10-Point API Security Best Practices Comparison

API Security Test 🔄 Complexity & Resources 📊 Expected Outcome 💡 Ideal Use Case ⭐ Key Advantage
API Inventory and Shadow/Zombie API Discovery Medium–high; passive research plus scoped active enumeration Documented attack surface and undocumented or outdated endpoints Establishing assessment scope and finding overlooked API versions or hosts Reveals endpoints that may lack current security controls
Broken Object Level Authorization (BOLA) Medium; requires multiple accounts and seeded test data Evidence of unauthorized access to another user's objects APIs handling user-, tenant-, or account-owned records Produces clear, reproducible proof of cross-account access
Function-Level Authorization (BFLA) and Role Boundaries Medium–high; requires role mapping and careful testing of privileged actions Identification of unauthorized access to restricted functions APIs with multiple roles, administrative routes, or privileged operations Can uncover vertical privilege escalation and administrative access
Authentication, Token Handling, and OAuth 2.0 High; requires access to authentication flows and often manual review Findings involving token forgery, replay, weak lifecycle controls, or OAuth weaknesses APIs using JWTs, OAuth, sessions, or machine-to-machine authentication Addresses flaws that can enable broad or persistent account access
Excessive Data Exposure and Mass Assignment Medium; requires response comparison and controlled request changes Identification of unnecessary data exposure or unauthorized field changes APIs that return broad object data or accept JSON create/update requests Can reveal privacy leaks and privilege or financial manipulation paths
Rate Limiting and Resource Consumption Medium–high; requires agreed request budgets and operations coordination Measured throttling gaps, abuse paths, or excessive response limits Login, OTP, search, export, upload, and paid-service endpoints Quantifies potential service disruption and direct cost abuse
Input Validation, Injection, and SSRF High; requires payload testing and careful scoping Evidence of injection, unsafe input handling, or server-side request access APIs handling queries, files, XML, URLs, or cloud-hosted requests May expose database, internal service, or cloud-resource compromise paths
GraphQL Introspection, Depth, and Batching Medium–high; requires schema-aware testing and bounded queries Findings in schema exposure, query limits, batching, or resolver authorization GraphQL APIs with flexible queries, nested data, or mutations Maps schema and can reveal authorization or rate-limit gaps
Security Misconfiguration: CORS, Headers, TLS, and Debug Exposure Low–medium; mostly configuration and endpoint checks Identification of exposed debug tools, weak transport settings, or unsafe policies Baseline API reviews and compliance-oriented assessments ⚡ Often quick to test and can produce actionable findings
Unsafe Consumption of Third-Party APIs High; often needs partner cooperation or sandbox access Findings in upstream data validation, webhook trust, or outbound requests APIs integrating with payment, identity, messaging, or partner services Extends testing across trust boundaries in API ecosystems

Turn API Testing Into a Repeatable Service

A one-time penetration test can identify serious flaws, but it can't establish that those flaws stay fixed as routes, schemas, authentication flows, and infrastructure change. A durable program preserves the endpoint inventory, the identities used in testing, the authorization rules verified, and the evidence needed to reproduce each finding. When the API changes, testers can rerun relevant scenarios instead of rebuilding the engagement from memory.

Automation is strongest where the check is repeatable: discovering candidate endpoints, replaying known authorization cases, validating configuration, and packaging request-response evidence. Human review remains essential for deciding whether a role should access a business function, whether a data field is sensitive in context, or whether a workflow can be abused despite behaving correctly at the protocol level. Scanners can support coverage, but they don't replace a tester who understands the application's tenant boundaries and business rules.

For MSSPs, that separation makes delivery more consistent without flattening every assessment into a generic scan. Automated evidence collection can standardize how the team records requests, responses, identities, and remediation status. Expert-led analysis can then focus on the places where permission depends on ownership, workflow state, or relationships between objects.

A practical starting point is to select one client API, document its identities and object relationships, and run the first four practices as a proof of concept. Confirm the scope in writing, use test data, and agree on evidence-handling rules before testing. Then turn the verified cases into scheduled regression tests and client-ready reporting, revisiting them whenever a release changes authentication, routes, schemas, or infrastructure.

The result isn't a substitute for a full security program. It's a repeatable assessment workflow that ties discovery to tested controls and gives developers evidence they can act on. Keep the inventory current, validate fixes rather than accepting status updates, and make each retest specific enough to show whether the original boundary now holds.


ThreatExploit AI supports automated penetration testing for REST and GraphQL APIs, with reconnaissance, testing, evidence collection, and compliance-mapped reporting for security service providers. Review how it can fit into your API assessment workflow by visiting ThreatExploit AI.