API Hacking Guide: How to Test APIs for Security Flaws (BOLA, JWT & GraphQL)
Learn API hacking step by step: discover endpoints, test authentication and authorization, find BOLA flaws with a worked crAPI example, test JWTs and GraphQL, and report findings — with tools, a cheat sheet and a checklist.
When an API Trusts the Wrong Caller
A mobile app opens a profile screen and requests user 123 from its backend. The server checks that the caller is logged in, finds the requested record, and returns it. Everything looks normal—until a tester changes 123 to 124 and receives a different user’s profile.
The app never offered a button for viewing someone else’s private account. That did not matter: the API trusted an object identifier without checking ownership.
API hacking means testing application programming interfaces for security flaws, legally, on systems you own or have written permission to test. It includes examining authentication, authorization, input handling, data exposure, and business rules. Practice only in isolated labs such as OWASP Juice Shop and crAPI, or within the explicit scope of an authorized assessment or bug bounty program.
This guide uses localhost and test-user data. The goal is to understand failures, produce minimal evidence, and help developers fix them—not collect other people’s information.
What Is API Hacking?
API hacking examines whether an application’s machine-facing interface enforces its security rules. An API lets software request data or perform actions without navigating a traditional web page. A mobile app, browser application, automation script, and partner integration can all communicate with the same backend.
How APIs Work in Five Lines
/api/v1/profile.Different API styles expose different testing opportunities:
| Style | Typical structure | Security testing focus |
|---|---|---|
| REST | Resource-oriented HTTP endpoints, commonly using JSON | Object permissions, HTTP methods, input validation, and response fields |
| GraphQL | Queries and mutations sent to a shared endpoint | Field-level authorization, schema exposure, query cost, and mutation permissions |
| SOAP | Structured XML messages, often described by WSDL | Authentication, operation permissions, XML handling, and message validation |
APIs can create a larger practical attack surface than visible web pages because they expose operations directly. Hidden buttons, disabled form fields, and mobile-only features provide no protection against a manually constructed request.
The same backend may support several clients and API versions, increasing the number of paths developers must secure. API security testing therefore asks more than “Can I log in?” It asks which objects, properties, and actions each identity may access—and whether the server independently enforces those decisions.
How API Hacking Works: The Methodology
Use a repeatable workflow rather than changing random parameters. Keep a request inventory, record expected behavior, and compare results between controlled accounts.
Step 1: Discover Endpoints
Start with documented routes, application traffic, and API references provided for the assessment. Inspect JavaScript bundles and requests captured in Burp Suite to identify additional paths. Prefer passive discovery before approved, low-rate endpoint enumeration.
Step 2: Map the API
Record each endpoint’s method, parameters, body format, authentication requirement, and response structure. Note relationships between users, organizations, projects, files, and other objects. A simple inventory prevents you from overlooking alternate methods or older API versions.
Step 3: Test Authentication
Check whether protected routes reject missing, expired, malformed, and invalid credentials. Examine login, logout, password reset, and token refresh behavior using disposable accounts. Distinguish authentication failures from application errors: a response code alone does not prove that a session was properly rejected.
Step 4: Test Authorization and BOLA
Create two test users and objects owned by each. Replay user A’s request with user B’s known object identifier while retaining A’s credentials. Test both reading and changing objects, but use disposable records and avoid destructive actions unless explicitly authorized.
Step 5: Test Input Handling
Try controlled variations in types, lengths, unexpected properties, and malformed structures. Determine whether the server rejects invalid input consistently instead of trusting client-side validation. Watch for verbose errors and unintended property updates without sending high-impact payloads.
Step 6: Test Business Logic and Rate Limits
Check whether valid requests can violate workflow rules—for example, using an expired discount or skipping an approval step. Test limits with small, agreed request counts rather than flooding the service. Record whether restrictions apply to the account, operation, or another documented boundary.
The result should be an evidence-backed map of security decisions, not merely a list of unusual responses.
Setting Up Your API Hacking Lab
Install Docker Engine, the Docker Compose plugin, and Python 3. On Kali, prepare Burp Suite or OWASP ZAP for interception, curl for reproducible requests, Postman for collections, and ffuf for carefully limited discovery.
Use intentionally vulnerable applications only on a machine you control. Do not expose their ports through a router, public cloud firewall, or shared development gateway.
Start crAPI Locally — Lab Only
Download the official OWASP crAPI source and extract it into a directory named crAPI. The commands below assume you are in its parent directory. crAPI stands for Completely Ridiculous API and is intentionally insecure.
This setup renders the project’s Compose configuration and forces every published port to bind to loopback:
# LAB ONLY: requires Docker Compose with JSON config output.
cd crAPI/deploy/docker
docker compose config --format json > compose.resolved.json
python3 - <<'PY'
import json
from pathlib import Path
config = json.loads(Path("compose.resolved.json").read_text())
for service in config["services"].values():
for port in service.get("ports", []):
port["host_ip"] = "127.0.0.1"
Path("compose.local.json").write_text(json.dumps(config, indent=2))
PY
docker compose -f compose.local.json pull
docker compose -f compose.local.json up -d
docker compose -f compose.local.json ps
The standard deployment exposes the application at http://localhost:8888 and its development mail interface at http://localhost:8025. Confirm the published addresses in the command output.
Start Juice Shop Locally — Lab Only
Use a separate terminal:
# LAB ONLY: publish Juice Shop only on loopback.
docker run --rm -d \
--name juice-shop \
-p 127.0.0.1:3000:3000 \
bkimminich/juice-shop
Open http://localhost:3000. Keep test credentials separate from real passwords. Stop Juice Shop with docker stop juice-shop; stop crAPI from its deployment directory with docker compose -f compose.local.json down.
Worked Example: Finding a BOLA Vulnerability
Broken Object Level Authorization, or BOLA, happens when an API accepts an object reference without checking whether the caller may access that object.
Important accuracy note: the numbered route /api/v1/user/123 below is illustrative, not a documented stock crAPI endpoint. crAPI uses its own routes and identifiers. Capture an actual object request in your installed lab and apply the same comparison there; do not expect these teaching URLs to work unchanged.
Step 1: Prepare Two Test Accounts
Start crAPI using the setup above. Register test user A and test user B, completing any verification through the local development mail interface.
Create separate browser sessions or profiles so their credentials do not become mixed. Record an object owned by each account through normal application behavior. Knowing both owners makes the result meaningful: changing to an arbitrary identifier and receiving 404 proves little.
Step 2: Capture User A’s Request
Configure the browser to use Burp’s proxy, commonly 127.0.0.1:8080. Browse the lab as user A and find a request that retrieves a user-owned object. Send it to Repeater, preserve the baseline, and identify the object reference.
Illustrative request: localhost only; test user A only. TEST_USER_A_TOKEN is a stand-in for a locally captured credential.
GET /api/v1/user/123 HTTP/1.1
Host: localhost:8888
Authorization: Bearer TEST_USER_A_TOKEN
Accept: application/json
Step 3: Change Only the Object Identifier
Keep user A’s authentication unchanged. Replace A’s identifier with the known identifier belonging to test user B. Changing the token too would test a different question.
Illustrative modified request: localhost only; test-user objects only.
GET /api/v1/user/124 HTTP/1.1
Host: localhost:8888
Authorization: Bearer TEST_USER_A_TOKEN
Accept: application/json
Step 4: Compare the Result
A secure implementation should deny access or deliberately conceal the object’s existence. If the following private profile is returned to user A, the example demonstrates unauthorized cross-user access.
Illustrative API response: localhost lab only; fictional test-user data only.
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 124,
"displayName": "Test User B",
"email": "test-user-b@example.com"
}
A 200 response is not automatically a vulnerability: the object might intentionally be public. Confirm the expected privacy rule before reporting.
Step 5: Reproduce with curl
Illustrative localhost requests only. Use the actual captured route in crAPI; the numbered teaching route may return 404 because it does not exist.
read -r -s -p "Paste test user A's lab token: " TOKEN
echo
curl -i \
-H "Authorization: Bearer $TOKEN" \
http://localhost:8888/api/v1/user/123
curl -i \
-H "Authorization: Bearer $TOKEN" \
http://localhost:8888/api/v1/user/124
The flaw is not predictable IDs. It is the missing server-side ownership or permission check. Fix it by authorizing every object access against the authenticated identity, tenant, and applicable role. UUIDs can reduce guessing but cannot replace authorization.
The OWASP API Security Top 10 (2023)
The OWASP API Security Top 10 is a risk framework, not a complete test plan. Use it to organize coverage while retaining application-specific business rules.
| Item | Description | One-line test idea |
|---|---|---|
| API1: Broken Object Level Authorization | Callers access objects outside their permissions. | Swap identifiers between two controlled users. |
| API2: Broken Authentication | Identity verification or session handling fails. | Check missing, invalid, expired, and logged-out credentials. |
| API3: Broken Object Property Level Authorization | Callers read or change unauthorized object properties. | Compare returned fields and accepted updates across roles. |
| API4: Unrestricted Resource Consumption | Requests consume excessive computing or other resources. | Check documented size and complexity limits with small inputs. |
| API5: Broken Function Level Authorization | Callers execute functions reserved for another role. | Replay an administrative request as a regular test user. |
| API6: Unrestricted Access to Sensitive Business Flows | Automated access abuses legitimate business operations. | Check controls around repeated reservations or promotions. |
| API7: Server Side Request Forgery | An API fetches attacker-controlled destinations unsafely. | Use a harmless, controlled destination to verify restrictions. |
| API8: Security Misconfiguration | Unsafe defaults or deployment settings expose the service. | Inspect debug errors, unnecessary methods, and header policies. |
| API9: Improper Inventory Management | Forgotten endpoints or versions remain accessible. | Compare deployed routes with the approved inventory. |
| API10: Unsafe Consumption of APIs | A service trusts third-party API data too much. | Use a mocked upstream response to check validation and timeouts. |
BOLA
BOLA is usually tested by holding identity constant while changing an object reference. Include identifiers in paths, query strings, request bodies, and nested relationships. The core check is: “Can test user A read or modify a private object owned by test user B?” Test ownership, tenant boundaries, and role permissions separately because each can fail independently.
Broken Authentication
Authentication testing covers more than the login form. Check token validation, reset flows, session invalidation, and whether credentials are accidentally accepted through inappropriate locations. A useful baseline command is curl -i http://localhost:8888/api/v1/user/123 without credentials, using an actual protected lab route. Confirm no protected data or action is available—not merely that the status code looks correct.
Excessive Data Exposure
Excessive Data Exposure was a named category in the earlier OWASP API list; related problems now fall under API3, Broken Object Property Level Authorization. Inspect complete JSON responses rather than only fields displayed by the application. Check whether regular users receive internal notes, recovery information, or administrative flags they should never see. Developers should explicitly select permitted response properties instead of serializing entire database objects.
Broken Function Level Authorization
Function-level authorization concerns actions rather than individual object ownership. A regular user might be denied another user’s profile but still reach an administrative export function. Capture a privileged action using an authorized administrative test account, then replay it with the regular account’s credentials. Use harmless or reversible operations and verify that authorization applies regardless of method or route variation.
Testing Authentication and JWTs
JSON Web Tokens are common in API authentication, but their presence does not guarantee secure sessions.
How JWTs Work in Five Lines
Common mistakes include accepting alg: none, using weak shared signing secrets, failing to enforce expiration, and placing sensitive information in readable payloads. Servers must also restrict acceptable algorithms and validate the intended issuer and audience.
Inspect and Modify a Lab Token
Burp can help capture and edit tokens. jwt.io can explain token structure, but never paste production credentials or sensitive tokens into an external website; use dummy tokens there or decode locally.
This command decodes a lab token without verifying its signature:
python3 - <<'PY'
import base64
import json
token = input("Paste a lab JWT: ").strip()
for label, part in zip(("header", "payload"), token.split(".")[:2]):
decoded = base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))
print(label, json.dumps(json.loads(decoded), indent=2))
PY
In Burp, change a harmless claim while retaining the original signature. Save the altered JWT as modified-token.txt, then replay against an actual protected localhost endpoint:
curl -i \
-H "Authorization: Bearer $(cat modified-token.txt)" \
http://localhost:8888/api/v1/user/123
The server should reject the modified token. Also test a genuinely expired lab token; simply editing its expiration invalidates the signature and does not isolate expiration handling. Review secret strength through authorized configuration inspection rather than uncontrolled guessing.
GraphQL API Hacking
GraphQL often exposes one endpoint through which clients select fields and invoke mutations. This changes discovery: an endpoint list alone may hide a large collection of operations.
Introspection lets clients query schema information, including available types and operation names. Its availability is not automatically a vulnerability. The important questions are whether sensitive capabilities are exposed and whether every resolver enforces authorization.
Run a Small Introspection Query
Use this only if your localhost lab actually provides /graphql; do not assume stock crAPI or Juice Shop exposes this route. Include the lab’s required authentication header when appropriate.
curl -s http://localhost:8888/graphql \
-H 'Content-Type: application/json' \
--data-binary @- <<'JSON'
{
"query": "{ __schema { queryType { name } mutationType { name } types { name kind } } }"
}
JSON
Review mutation names, administrative operations, and types representing sensitive records. Then request only a small set of test-user fields and compare access between controlled identities.
GraphQL authorization must apply to nested fields and relationships, not just the top-level query. An allowed project query must not expose a forbidden owner field through a nested resolver.
Also review query depth, complexity, pagination, and batching controls. Test these with small, approved requests; do not build deeply recursive queries against shared services. Disabling introspection may reduce discovery, but it does not repair authorization or resource-limit failures.
API Hacking Tools
Choose tools by task. Automatic findings require manual confirmation, and some scanners can send state-changing requests.
| Tool | What it does | When to use it |
|---|---|---|
| Burp Suite | Intercepts, edits, and replays HTTP traffic | Manual authentication and authorization comparisons |
| OWASP ZAP | Provides an intercepting proxy and scanning features | Passive inspection and explicitly approved scanning |
| Postman | Organizes requests, environments, and workflows | Repeatable multi-step API tests |
| curl | Sends precise HTTP requests from a terminal | Minimal reproductions and shell automation |
| ffuf | Fuzzes paths, parameters, and other request positions | Bounded discovery with small wordlists |
| Arjun | Helps discover HTTP parameter names | Investigating undocumented input parameters |
| Kiterunner | Performs route-aware API discovery | Approved discovery where method and path context matter |
| Nuclei | Runs template-based security checks | Carefully selected, reviewed checks within scope |
Keep separate environments for each test identity. Disable automatic redirects when investigating credential forwarding, and review scanner settings before execution. Tool output is a lead, not proof of exploitability.
API Hacking Cheat Sheet
The routes below are illustrative localhost teaching paths, not guaranteed crAPI endpoints. Replace them with captured lab routes. $TOKEN means a token belonging to your test account; app.js and params.txt are local files you prepare.
| Task | Command / check |
|---|---|
| curl basics | curl -i http://localhost:8888/ |
| Get endpoints from JavaScript | grep -En '(/api/|/graphql)' app.js |
| Test BOLA | Replay user A’s request with user B’s known private object ID. |
| Test authentication | Remove the authorization header and confirm protected access is denied. |
| Test rate limits | Send a few approved requests slowly; inspect limits and Retry-After. |
| Fuzz parameters | ffuf -u 'http://localhost:8888/api/v1/user/123?FUZZ=test' -w params.txt -rate 2 |
| Check HTTP methods | curl -i -X OPTIONS http://localhost:8888/api/v1/user/123 |
| Test mass assignment | Add one unauthorized property to a disposable object update; verify stored state. |
| Check CORS | curl -i -H 'Origin: https://example.com' http://localhost:8888/api/v1/user/123 |
| Test GraphQL introspection | Send the small __schema query shown above to an observed GraphQL route. |
| Check API keys in JavaScript | grep -Ein '(api[_-]?key|secret|token)' app.js |
| Test pagination abuse | Check modest page sizes against documented maximums. |
| Check error messages | Send one malformed field; look for stack traces or internal details. |
| Test versioning | Compare known deployed versions for equivalent authentication and authorization. |
| Test file uploads | Upload a harmless small file and check type, size, storage, and retrieval permissions. |
Use a tiny parameter wordlist and avoid state-changing fuzzing. Search matches do not prove a secret is present; browser applications may contain intentionally public identifiers. An OPTIONS response does not prove other methods are safe, and curl cannot reproduce browser CORS enforcement by itself.
Troubleshooting API Tests
Before reporting a flaw, rule out request-format problems and mixed identities.
| Problem | Likely cause | Fix |
|---|---|---|
401 on every request | Missing, expired, or incorrectly formatted credentials | Capture a fresh successful request and preserve its authentication format. |
403 after login | Valid identity lacks permission, or another protection rejects the request | Check roles, ownership, CSRF requirements, and documented policy. |
| Empty responses | 204, wrong method, or compression/display handling | Inspect status and headers; compare with a working baseline. |
| Rate limited | Request frequency exceeded an enforced limit | Stop, honor Retry-After, and reduce the agreed testing rate. |
| CORS errors | Browser origin restrictions block frontend access | Inspect preflight and response headers; do not confuse CORS with authorization. |
| Token expires mid-test | Short-lived sessions or rotation | Refresh through the normal flow and record credential timing. |
| Burp not intercepting app traffic | Proxy bypass, wrong settings, or certificate trust issues | Use Burp’s browser; verify proxy routing and lab certificate trust. |
| API returns HTML instead of JSON | Wrong path, redirect, frontend fallback, or login page | Inspect redirects, route prefixes, and Content-Type. |
For mobile certificate pinning, use an approved test build or documented lab configuration. Do not assume bypassing a transport control is within scope.
How to Report and Fix API Flaws
A useful API penetration testing report lets another person reproduce the issue without guessing.
Include:
Avoid including complete datasets or usable credentials. One controlled object is usually enough to establish an authorization failure.
Developer Fixes by Flaw Class
For BOLA and function-level failures, enforce server-side policy on every request and object. Scope database queries to the authorized identity or tenant rather than fetching unrestricted objects first.
For property-level failures, use explicit input and output field allowlists. Reject unauthorized updates even if the client interface hides those fields.
For input handling, validate types, ranges, sizes, and structure; use parameterized database access. For resource abuse, enforce request-size limits, bounded pagination, timeouts, and operation-aware rate limits.
For token security, use maintained libraries, strict validation, short-lived access tokens, and least-privilege scopes. Add regression tests using multiple identities so the same flaw does not return through another endpoint.
Common Mistakes
Summary
API hacking tests whether a backend enforces its security rules independently of its clients. A reliable workflow discovers routes, maps behavior, and examines authentication, authorization, inputs, and business logic. BOLA testing requires controlled identities and known object ownership, not random identifier guessing. Burp, curl, and other tools help reproduce findings, but manual context determines their significance. Practice only within written authorization and report minimal evidence with clear remediation.
Knowledge Check
Answers: 1. The identity of the caller. 2. Which objects, properties, and actions that caller may access. 3. User A's credentials with user B's known private object identifier. 4. No; object access still requires server-side authorization. 5. No; signed JWT payloads are normally readable. 6. No; exposure and authorization must be assessed in context. 7. API3, Broken Object Property Level Authorization. 8. Minimal reproducible evidence, clear impact, and an actionable fix.
Keep Learning
Frequently Asked Questions
Continue Learning
JWT Security: What Is a JWT, Common Attacks & How to Test Them
What is a JWT? Learn JWT security: how JSON Web Tokens work, the none and algorithm confusion attacks, and how to test JWTs with jwt_tool and Burp Suite.
Web Security · IntermediateWhat Is XSS? Cross-Site Scripting Examples & How to Prevent XSS Attacks
Learn what XSS is, its types, and how to prevent XSS with a worked DVWA example, context-aware defenses, testing tips, and a cheat sheet.
Web Security · BeginnerOWASP Top 10 2025: All 10 Risks Explained With Examples & How to Test Them
OWASP Top 10 2025 explained: all 10 risks with real examples, what changed from 2021, and how to test each one in Kali Linux, plus a cheat sheet.
Web Security · IntermediateWhat Is SQL Injection? Types, Examples & How to Prevent SQL Injection Attacks
What is SQL injection? See real SQL injection examples, a worked DVWA lab test, and how to prevent SQL injection with parameterized queries.
Related Security Tools
Security Headers Checker
Check HTTP security headers (CSP, HSTS, X-Frame-Options, X-XSS-Protection, Referrer-Policy, and more) with security scoring.
Web SecuritySSL Certificate Checker
Check SSL/TLS certificate details including issuer, expiration date, days remaining, validity, and security grade.
Web SecurityWebsite Security Score
Generate a comprehensive 0-100 security score based on SSL status, security headers, domain age, and DNS configuration.
Web ApplicationFFUF
Learn how to use FFUF (Fuzz Faster U Fool), the extremely fast open-source web fuzzer written in Go: place the FUZZ keyword where a wordlist entry should go, run your first scan, filter the noise, and discover hidden directories, files, parameters, virtual hosts and API endpoints on targets you have permission to test.