API Security & Auth Testing

API Security Testing: What It Is and How to Do It

Rishi GauravUpdated Oct 19, 202618 min read

Quick answer

API security testing checks that an API resists attack: that it rejects missing or forged credentials, refuses one user access to another user's data, validates every input, leaks nothing it should not, and limits abuse. Use the OWASP API Top 10 as the baseline, run automated checks on every change in CI/CD, and add periodic penetration tests for business logic.

Reviewed by Smeet Gohel

Share:
API security testing guide with shield and lock icons

API security testing is the practice of checking that an API resists attack. A secure API rejects missing, expired and forged credentials. It refuses one user access to another user's objects and to operations above their role, validates every input, exposes no data it shouldn't, and limits abuse. A working program combines automated checks on every change with periodic manual penetration testing, and uses the OWASP API Security Top 10 as its minimum test plan. This is the pillar of our Security & Auth hub. If you're comparing scanners rather than learning the practice, start with API security testing tools compared.

APIs are attractive targets for a simple reason. Every request is scriptable, every identifier is visible in the payload, and the authorization decision a user interface hides is made fresh on every call. Testing security once a quarter can't keep pace with an API that changes every day. That's why most of this guide is about tests that run on every change.


In this guide

  1. What is API security testing?
  2. The OWASP API Top 10 as a test plan
  3. How to do API security testing, step by step
  4. Example test cases: BOLA, BFLA and unauthenticated access
  5. API penetration testing vs API security testing
  6. API security testing in CI/CD pipelines
  7. API security testing tools
  8. Challenges and how to solve them
  9. API security testing FAQ

What is API security testing?

Functional API testing checks that an API does what it should. Security testing checks that it refuses to do what it shouldn't, when the caller is wrong, malicious or curious. The discipline uses four methods, each of which finds a different class of problem:

MethodWhat it examinesWhat it findsWhen it runs
SAST (static analysis)Source code, configuration and the OpenAPI document, without running anythingHard-coded secrets, missing auth annotations, insecure patterns, a spec that marks a sensitive operation as publicEvery commit
DAST (dynamic testing)The running API, by sending crafted requestsInjection, broken authentication, missing headers, verbose errors, misconfigurationEvery build or deployment to a test environment
IAST (interactive testing)The application from inside while tests runWhich inputs reach which code paths, with fewer false positivesDuring automated test runs
Manual penetration testingThe whole attack surface, by a human acting as an attackerBusiness-logic flaws and chained attacks no tool reasons aboutPeriodically, and after major changes

The goal isn't to find every theoretical weakness. It's to keep checking the most damaging risks continuously as the API evolves, and to use human testers where judgment is needed.


The OWASP API Top 10 as a test plan

The OWASP API Security Top 10 (2023) is the closest thing the industry has to a minimum test plan. Each risk maps to concrete tests:

RiskWhat to test
API1 Broken object level authorization (BOLA)User B requests user A's object by ID and must be refused. Walk neighbouring IDs. Repeat for write and delete.
API2 Broken authenticationNo token, malformed token, expired token, bad signature, wrong issuer or audience, alg: none, token in the query string, refresh-token replay, sign-out actually revoking the session.
API3 Broken object property level authorizationMass assignment (sending role or isAdmin in a body), and responses that return fields the caller shouldn't see.
API4 Unrestricted resource consumptionBursts against rate limits, oversized bodies, unbounded page sizes, expensive GraphQL queries, and burst limits on login, reset and one-time-code endpoints.
API5 Broken function level authorization (BFLA)A lower-privileged user calls admin or management operations, and undocumented methods.
API6 Unrestricted access to sensitive business flowsReplay a one-time step, skip or reorder steps, reuse an idempotency key, race a one-time operation.
API7 Server-side request forgery (SSRF)URL fields refuse cloud metadata addresses, loopback and private ranges, and encoded variants.
API8 Security misconfigurationHSTS, nosniff, cache headers, CORS reflecting arbitrary origins, verbose errors, TLS versions, exposed debug and spec endpoints.
API9 Improper inventory managementRetired versions that still answer, shadow endpoints missing from the spec.
API10 Unsafe consumption of APIsResponses from upstream APIs validated before use.

Injection isn't its own category in the 2023 list, but SQL, NoSQL, command, template and XML injection still belong in the plan. Each risk is explained with its own test cases in OWASP API Top 10 vulnerabilities and how to test them. The control-to-audit mapping is in OWASP API Top 10 enterprise controls.


How to do API security testing, step by step

1. Build the inventory. You can't test an API you don't know exists. Collect every OpenAPI document, then compare them with gateway configuration and traffic to find shadow and retired endpoints. Require a maintained spec before an API can be deployed.

2. Threat-model the sensitive flows. For each API, list the data it holds, who should reach it, and the business flows that would hurt if abused (payments, account changes, one-time operations). That list decides where manual effort goes.

3. Set up identities, plural. Authorization tests need at least two users of the same role (for BOLA) and users of different roles (for BFLA), plus an anonymous caller. Scanners that run with a single credential can't find the most common API flaw. Authentication itself deserves dedicated tests. See how to test API authentication and authorization, the JWT testing guide, and OAuth testing best practices with its companion on OAuth negative testing against an enterprise IdP.

4. Turn the Top 10 into automated checks. Generate or write the checks per endpoint: authentication probes, the access matrix (which role may do what to whose data), injection payloads for every parameter, response-field checks, and configuration checks. Rate limits need their own approach; see testing API rate limiting and throttling.

5. Scan the running API. Point a DAST tool at a test environment with the OpenAPI document so it knows every operation. Keep intrusive and data-changing probes on non-production environments only.

6. Commission manual penetration tests. Give the testers the spec, the threat model and test accounts, and scope the engagement to the API layer and business logic. Then turn every finding into an automated regression check.

7. Triage with recorded decisions. Each finding is fixed, accepted as a risk, or marked a false positive, and the reason is recorded. Review suppressions every quarter.

8. Keep secrets out of the tests. Credentials committed in test fixtures are a finding of their own. JWT secret leakage in test files covers how to find the ones already in your repositories.

How Shift-Left API does this: API security testing is a paid add-on to Professional and Enterprise licences, and the Trial includes it. It generates OWASP-mapped checks beside the functional tests a project already has, so they reuse the same endpoints, environments and authentication profiles. 94 of the 100 checks in its catalogue run on a standard install. BOLA, BFLA and tenant-isolation checks use a second labelled test user and an access matrix (Deny, Own data only or Allow per endpoint). Intrusive and data-changing checks stay off until an Administrator allows them for a specific non-production environment, and they never run against production. Each finding carries a CVSS v3.1 base score, OWASP API Top 10, ASVS and CWE mappings, evidence and a fix, and every report opens with what could not be checked. It detects with benign probes and isn't a penetration test.

Ready to shift left with your API testing?

Try our no-code API test automation platform free. Generate tests from OpenAPI, run in CI/CD, and scale quality.


Example test cases: BOLA, BFLA and unauthenticated access

Broken object level authorization (API1) and broken function level authorization (API5) are the risks a single-credential scanner can't see, because both need two identities:

# tests/test_authorization.py
import pytest, requests

API = "https://staging.example.com"

@pytest.fixture(scope="session")
def tokens():
    return {r: requests.post(f"{API}/login", json=CREDS[r]).json()["token"]
            for r in ("owner", "other", "viewer")}

@pytest.mark.parametrize("path", ["/v1/orders/{id}", "/v1/invoices/{id}"])
def test_bola_other_users_object_is_not_readable(tokens, path, owned_id):
    # API1:2023: the object exists, but it is not this caller's object
    r = requests.get(API + path.format(id=owned_id),
                     headers={"Authorization": f"Bearer {tokens['other']}"})
    assert r.status_code in (403, 404), f"BOLA: {path} leaked to a non-owner"

def test_bfla_viewer_cannot_reach_an_admin_operation(tokens):
    # API5:2023: the route is hidden in the viewer's UI, which is not a control
    r = requests.delete(f"{API}/v1/admin/users/7",
                        headers={"Authorization": f"Bearer {tokens['viewer']}"})
    assert r.status_code in (401, 403)

Add the unauthenticated baseline as a separate case. Every protected operation in the spec must reject a request with no credentials:

# every path in the spec, with no Authorization header, must be 401
yq -r '.paths | keys[]' openapi.yaml | while read -r p; do
  code=$(curl -s -o /dev/null -w '%{http_code}' "$API${p//\{*\}/1}")
  [ "$code" = "401" ] || echo "UNAUTHENTICATED ACCESS: $p -> $code"
done

A penetration tester does the same thing by hand and then keeps going: they guess that IDs are sequential, walk the range, and chain the leak into something worse.

# authenticate as user A, then walk IDs that belong to other users
TOKEN_A=$(curl -s -XPOST "$API/login" -d '{"u":"a","p":"..."}' | jq -r .token)
for id in $(seq 1000 1010); do
  code=$(curl -s -o /dev/null -w '%{http_code}' \
    -H "Authorization: Bearer $TOKEN_A" "$API/v1/orders/$id")
  echo "$id -> $code"     # any 200 for an object A does not own is a BOLA finding
done

API penetration testing vs API security testing

API security testing is a continuous practice. Automated checks for authentication, authorization, input handling, data exposure and configuration run on every change. API penetration testing is a time-boxed engagement, often one to three weeks, in which skilled testers act as attackers. They explore business logic, chain weaknesses and try to escalate privileges in ways a tool can't. Security testing answers "are our controls still working on this change?". Penetration testing answers "can a determined attacker get in right now?".

API security testingAPI penetration testing
CadenceEvery pull request, merge and deploymentPeriodically (annually or quarterly) and after major changes
WhoThe development team, through tools in the pipelineSpecialist testers, internal or external
MethodAutomated checks, DAST scans, spec-driven testsManual exploration with proxies, scripts and judgment
StrengthConsistent coverage of known risk classes on every changeBusiness-logic flaws, chained attacks, creative abuse
Blind spotLogic no tool understands, such as negative transfer amounts or reusing a discount twiceEverything that changes between engagements
OutputFindings in the pipeline, gates on merges and deploysA report of validated, exploitable findings

What is API penetration testing in practice? A pen test usually follows a methodology such as the OWASP Web Security Testing Guide. The steps are scoping and rules of engagement, reconnaissance (documentation, mobile clients, hidden endpoints and parameters), active testing through an intercepting proxy, and manual validation of every finding before it's reported.

Use both, deliberately. Relying only on an annual pen test leaves every change between engagements untested. A BOLA introduced the week after a pen test can live in production until the next one. Relying only on automation misses the logic flaws that need human context. The pattern that works:

  • Automated security checks gate every change.
  • Pen tests are scoped to business logic and the highest-risk APIs, with the spec and test accounts provided up front.
  • Every pen test finding becomes an automated regression check, so it can't come back.

Compliance treats them differently. Frameworks such as PCI DSS distinguish penetration testing from vulnerability scanning. PCI DSS requirement 11.4 calls for periodic penetration testing that automated scanning doesn't satisfy. Automated testing gives you continuous evidence that controls were checked. It doesn't replace the pen test an assessor asks for.


API security testing in CI/CD pipelines

Security checks catch the most when they run where code changes, in the pipeline. Then the developer who introduced a weakness sees it in the same pull request, not in a report weeks later. The general pipeline wiring is covered in API testing in CI/CD. Security adds a few specifics.

Tier the scans by trigger:

TierTriggerWhat runsBudgetGate
1Every pull requestAuthentication and authorization checks, input checks on changed endpoints, spec audit5 to 10 minutesBlock on new critical findings
2Merge to mainFull OWASP API Top 10 coverage, rate-limit and response-field checks15 to 30 minutesBlock deploy on new critical or high findings
3Nightly or weeklyDeep DAST scans, brute-force and lockout checks, cross-service authorizationAs long as neededReport and ticket

Gate on new findings, not the backlog. Turning a security gate on usually surfaces older findings. A gate that fails on all of them gets switched off within a week. Baseline existing findings with owners and due dates, and block only on findings a change introduces.

Export in formats the pipeline understands. SARIF feeds GitHub code scanning and similar dashboards, and JUnit feeds the CI's test tab. Shift-Left API's security findings export as both. On a self-hosted install, its headless runner can also fail a build on findings at or above a chosen severity, and on new findings only; confirm availability with support.

Solve authentication once. Pipelines need credentials that work headlessly: service accounts, the OAuth 2.0 client-credentials grant, or a scripted sign-in, stored as pipeline secrets and never in the repository. Multi-step and MFA sign-ins are where scripted approaches usually break, so prefer a tool that can hold a reusable sign-in profile per test user. SSO and secret management for API testing covers the OIDC-to-vault pattern.

A spec-driven DAST scan on the pull request with the OWASP ZAP API scan action:

# .github/workflows/api-security.yml
name: API security
on:
  pull_request:
    paths: ['openapi.yaml', 'src/**']
jobs:
  dast:
    runs-on: ubuntu-latest
    permissions: { security-events: write }
    steps:
      - uses: actions/checkout@v4
      - name: Deploy PR preview
        run: ./scripts/deploy-preview.sh   # your own script; sets PREVIEW_URL
      - name: OWASP ZAP API scan
        uses: zaproxy/action-api-scan@v0.9.0
        with:
          target: '${{ env.PREVIEW_URL }}/openapi.yaml'
          format: openapi
          fail_action: true

Free ZIP: CSV pack + guide

OWASP API Top 10 Test-Case Pack

60 API security test cases mapped to the OWASP API Security Top 10 (2023): positive and negative cases for BOLA, broken auth, SSRF and misconfiguration.

Download Free

API security testing tools

ToolTypeBest forOpen source
OWASP ZAPDASTSpec-driven scanning in CI, plus manual explorationYes
Burp SuiteDAST / manualPenetration testing through an intercepting proxyCommunity edition free
NucleiTemplate scannerCustom checks as codeYes
Semgrep, SonarQubeSASTCode-level security patternsPartly
42CrunchSpec audit + conformanceAuditing the OpenAPI document itselfNo
StackHawkDASTDeveloper-first DAST in CINo
PostmanFunctionalScripted negative tests in collectionsFree tier
Shift-Left APIGenerated checks (paid add-on)OWASP-mapped checks beside existing functional tests, multi-user authorizationNo

The full comparison, with pricing models, CI integration and protocol coverage, is in API security testing tools compared. Most mature programs combine a fast tool on pull requests, a deep open-source scanner on a schedule, and manual testing on top. If your APIs include MCP servers for AI agents, they need their own checks; see MCP server security testing.


Challenges and how to solve them

Incomplete API inventory

Shadow and zombie APIs are never tested because nobody knows they exist. Solution: discover endpoints from gateway logs and traffic, compare them with the registered specs, and require a spec before deployment.

False positives overwhelm the team

Untuned scanners flag patterns that aren't exploitable, and developers stop reading the findings. Solution: tune scan policies to your stack, prefer spec-aware tools, triage by severity and exploitability, and keep every suppression a human decision with a recorded reason. Review suppressions every quarter.

A probe that never reached the API is reported as a pass

A WAF, gateway, login redirect or rate limiter can answer a security probe before it reaches your code. A naive tool then reports "no vulnerability". Solution: use tools that report such checks as not evaluated, and read that section of the report first.

Testing authenticated endpoints

OAuth chains, MFA and custom sessions defeat many scanners. Solution: configure authentication contexts up front, use dedicated test accounts for each role, and handle token refresh in the tooling rather than in brittle pipeline scripts.

Keeping tests current as the API changes

Security tests written last quarter miss this quarter's new parameters. Solution: generate checks from the OpenAPI spec so new operations are covered when they appear, and re-scan the endpoints a spec change touches.

Scans overload shared environments

Burst and fuzzing checks can degrade a shared staging environment and produce unreliable results. Solution: run intensive checks in dedicated environments or off-peak, test critical endpoints first, and keep data-changing checks away from production entirely.


More from the API Security & Auth Testing hub

Every guide in this hub, grouped by format. The API Security & Auth Testing hub page has the full list.

Tools and comparisons

Checklists, templates and test cases

API security testing FAQ

What is API security testing?

API security testing is the practice of checking that an API resists attack. It rejects missing, expired or forged credentials, stops one user reaching another user's data or admin operations, validates every input, exposes no data it shouldn't, and limits abuse. It combines automated checks on every change with periodic manual penetration testing.

How do you do API security testing?

Start from a complete API inventory and the OpenAPI spec. Map each OWASP API Top 10 risk to test cases, and set up at least two test users so authorization can be tested. Run automated authentication, authorization, input and configuration checks on every change, scan the running API with a DAST tool, and commission manual penetration tests for business logic.

What is the difference between API penetration testing and API security testing?

API security testing is the continuous, mostly automated practice of checking security controls on every change. API penetration testing is a time-boxed, manual engagement in which testers act as attackers, chain weaknesses and probe business logic. Security testing gives continuous coverage and pen testing gives adversarial depth, so you need both.

Can you do API security testing with Postman?

Partly. Postman collections can script negative tests, such as requests with no token, an expired token, another user's object ID or an injection payload, with assertions on the status code. That covers targeted checks, but Postman isn't a scanner, so pair it with a DAST tool and dedicated authorization tests.

How do you add API security testing to a CI/CD pipeline?

Run fast authentication, authorization and input checks on every pull request, a fuller DAST scan on merge to main, and deep scans nightly. Export findings as SARIF or JUnit, and block on new critical and high findings. Baseline existing findings so the gate can go live before the backlog is cleared.

What are API security testing best practices?

Use the OWASP API Security Top 10 as the minimum baseline. Test authorization with at least two identities and test every endpoint independently. Keep security tests in the pipeline rather than in a quarterly report, and never run destructive checks against production. Turn every penetration test finding into an automated regression check.


Sources and further reading

Key takeaways

  • API security testing checks that an API refuses what it should refuse: bad credentials, other users' data, admin operations, malicious input and abuse.
  • The OWASP API Top 10 is the minimum test plan. Authorization (BOLA and BFLA) needs at least two test identities, which single-credential scanners lack.
  • Security testing and penetration testing are complementary. Automate the first on every change, schedule the second, and turn every pen test finding into an automated check.
  • In CI/CD, tier the scans by trigger, gate on new findings, and export SARIF and JUnit so findings appear where developers work.

To generate OWASP-mapped security checks beside the functional tests you already run, including multi-user authorization checks, start a free 15-day trial. The Trial includes the API security testing add-on.


Related: OWASP API Top 10 Vulnerabilities and Tests | API Security Testing Tools Compared | How to Test API Authentication and Authorization | JWT Authentication Testing | OAuth API Testing | API Rate Limit Testing | API Security Testing Platform

For regulated teams: see API testing for SOC 2 controls, PCI DSS, HIPAA and the platform security & trust center.

Ready to shift left with your API testing?

Import your OpenAPI spec and get a runnable test suite, in our cloud or on your own infrastructure.