API Security Essentials: Authentication, Rate Limits and Testing

APIs (application programming interfaces) are the connective tissue of modern software. Mobile apps, single-page websites, partner integrations and microservices all talk through APIs, which means that a huge share of your data is one HTTP request away. APIs expose functions and data directly, often with less of the user-interface protection that hides weaknesses in a normal web page. This lesson covers how APIs work, the OWASP API Security risks, and a practical checklist for building and testing APIs safely.

API Basics for Security People

StyleFeaturesSecurity notes
REST (JSON over HTTP)Resources at URLs; methods GET, POST, PUT, PATCH, DELETEAuthorise per resource and per method; watch for object-level flaws
GraphQLSingle endpoint; clients ask for exactly the fields they wantLimit query depth and cost, control introspection, authorise at field level
SOAP / XMLStrict contracts, WS-SecurityDisable dangerous XML features (external entities), validate schemas
gRPCBinary protocol buffersStill needs authentication, authorisation and input validation
WebSockets / webhooksPersistent or event-driven channelsAuthenticate connections, verify webhook signatures

A first look at an API request

curl -i -X GET "http://127.0.0.1:3000/api/Products/1"      -H "Accept: application/json"

Read the response: status code, headers, body. Note anything unexpected, such as extra fields (internal IDs, flags, hashes) that the client did not need. Excess data exposure is among the most common API weaknesses.

OWASP API Security Top 10 (2023 Edition)

IDRiskIn plain words
API1Broken Object Level AuthorizationChanging an object ID returns someone else’s data
API2Broken AuthenticationWeak login, token or key handling
API3Broken Object Property Level AuthorizationReturning or accepting properties a user should not see or set
API4Unrestricted Resource ConsumptionNo limits on requests, size or cost, enabling abuse or denial of service
API5Broken Function Level AuthorizationNormal users can call admin functions
API6Unrestricted Access to Sensitive Business FlowsAutomated abuse of flows such as purchasing, voucher use or account creation
API7Server Side Request ForgeryAPI fetches attacker-supplied URLs
API8Security MisconfigurationVerbose errors, open CORS, missing headers, default settings
API9Improper Inventory ManagementForgotten old versions, test and shadow endpoints
API10Unsafe Consumption of APIsTrusting third-party API data without validation

Core Defences in Detail

1. Authentication and tokens

  • Use standard protocols: OAuth 2.0 and OpenID Connect rather than custom schemes.
  • Prefer short-lived access tokens and revocable refresh tokens.
  • Never place secrets or API keys in URLs, mobile app code or public repositories.
  • Protect login, password reset and token endpoints with rate limits and MFA where possible.

2. Authorisation at three levels

  • Object level: does this user own or may they access this record?
  • Property level: may they see or change this field, such as isAdmin or price?
  • Function level: may they call this endpoint or method?

See Broken Access Control and Session Flaws for code patterns.

3. Input validation and output filtering

  • Validate request bodies against a schema (JSON Schema, OpenAPI): types, lengths, ranges, allowed values.
  • Reject unknown fields to prevent mass assignment.
  • Return only the fields needed by the client, using explicit response models rather than dumping whole database objects.
  • Use parameterised queries to prevent injection; see SQL Injection Explained and Prevented.

4. Rate limiting and resource controls

  • Limit requests per user, key and IP address; stricter for expensive or sensitive endpoints.
  • Set maximum payload sizes, pagination limits and timeouts.
  • For GraphQL, limit query depth, complexity and batching.
  • Monitor for credential-stuffing patterns and automated abuse.

5. Transport and configuration

  • HTTPS only, with modern TLS and HSTS.
  • Restrictive CORS: allow-list named origins; never combine wildcards with credentials.
  • Return generic errors; keep stack traces out of responses.
  • Disable unused methods, debug endpoints and old API versions.

6. Inventory and governance

  • Maintain an API catalogue with owners, versions, data classification and authentication method.
  • Retire old versions deliberately.
  • Use an API gateway for central authentication, throttling, logging and policy.

Practice Lab 1: Explore an API in Your Lab

  1. Run Juice Shop locally (see the home lab lesson). Open developer tools, Network tab, and filter by XHR/fetch to see its API calls.
  2. For three requests, record: method, path, authentication method, request fields and response fields.
  3. Highlight any response field the interface never displays. Would a client truly need it?
  4. Classify each observation against the OWASP API Top 10 list above.

Practice Lab 2: Build a Small Secure API

Write a tiny API in a language you know (here a Python Flask sketch) and apply the defences:

from flask import Flask, request, jsonify, abort
app = Flask(__name__)

ALLOWED_FIELDS = {"display_name", "city"}     # allow-list for updates

@app.route("/api/me", methods=["PATCH"])
def update_me():
    user = authenticate(request)               # verify token, return user or abort(401)
    data = request.get_json(silent=True) or {}
    unknown = set(data) - ALLOWED_FIELDS
    if unknown:
        abort(400, "Unknown fields")           # blocks mass assignment such as {"role": "admin"}
    for key, value in data.items():
        if not isinstance(value, str) or len(value) > 50:
            abort(400, "Invalid value")
        setattr(user, key, value)
    save(user)
    # Return an explicit, minimal response model
    return jsonify({"display_name": user.display_name, "city": user.city})

Now write tests: a request with a role field must be rejected; a 10,000-character value must be rejected; a missing token must return 401.

Practice Lab 3: Add Rate Limiting

  1. Add a simple limiter (for example the Flask-Limiter library) allowing 5 login attempts per minute per client.
  2. Test with a loop that sends repeated requests to your own lab API:
    for i in $(seq 1 10); do curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:5000/api/login; done
    You should see the status change to 429 (Too Many Requests) once the limit is passed.
  3. Document the limits you chose and why.

Testing APIs Professionally

  • Start from the OpenAPI specification if available; compare documented behaviour with real behaviour.
  • Use tools such as Postman, Insomnia, Burp Suite or OWASP ZAP within your authorised scope.
  • Test with multiple users and roles, as described in the access control lesson.
  • Look for undocumented endpoints, old versions and verbose errors.
  • Check business flow abuse: repeated coupon use, bulk account creation, race conditions.

Common Mistakes

  • Trusting the front end to hide fields and functions.
  • Returning entire database records and relying on the client to filter.
  • Long-lived tokens that never expire.
  • Forgetting old API versions that remain online without protections.
  • No rate limits on login, reset and search endpoints.

Practice Exercises

  1. Match each OWASP API Top 10 item to one concrete example from an online shop.
  2. Explain the difference between object-level and function-level authorisation.
  3. Write a JSON Schema for a “create address” request that rejects unknown fields.
  4. Design rate limits for login, password reset and product search endpoints, and justify each.
  5. List the metadata you would record in an API inventory.

Mentor tip: If you can only do one thing for API security, build a test that logs in as User A and tries to read and change every object belonging to User B. Run it in your pipeline on every build.

Educational use only: test only APIs you own, deliberately vulnerable lab apps, or targets within written authorisation.

Key takeaways
  • APIs expose data and functions directly, so authorisation must be enforced at object, property and function level.
  • Use standard authentication, short-lived tokens, schema validation and minimal responses.
  • Apply rate limits and resource controls to prevent abuse.
  • Keep an API inventory and retire old versions.
  • Test with multiple accounts and automate the checks.

Related Lessons