API Security Best Practices Every Developer Should Follow

APIs account for 71% of web traffic, yet 78% of organizations suffered an API security incident in 2023. This guide covers authentication, authorization, rate limiting, and monitoring practices grounded in real breaches from Optus, T-Mobile, Facebook, and Peloton.

Every API starts the same way. A developer opens an editor, writes a route handler, connects it to a database, and tests whether it returns the right JSON. The demo works. The sprint review goes well. The endpoint ships to production. Nobody asks whether an unauthenticated caller can hit that endpoint, whether the response leaks fields it should not, or whether someone can call it ten thousand times per second. Those questions come later, usually after something breaks. In 2023 alone, 78% of organizations reported at least one API security incident. The breaches that followed cost between $4.1 million and $6.1 million on average.

The Way APIs Actually Get Built

Talk to any backend developer about how their last API endpoint went from idea to production, and you will hear a familiar pattern. The product manager writes a ticket. The developer builds the endpoint in a day or two. They test it against the happy path: valid input, expected output. The frontend team integrates it. QA runs through the user stories. Nobody writes a test for what happens when a caller sends a customer ID that belongs to someone else.

This is not laziness. It is the natural consequence of how software teams prioritize work. The first priority is always functionality. Does the endpoint do what the ticket says? The second priority is reliability. Does it handle known error cases? Security sits somewhere around the fifth or sixth spot, sandwiched between “write documentation” and “clean up the TODOs.” Sprint deadlines reinforce this. A developer who spends two extra days adding rate limiting, input schema validation, and authorization checks to an endpoint that “only our frontend calls” will hear the same question from the team lead: why did this take so long?

The result is predictable. APIs ship with hardcoded keys that were supposed to be temporary. Endpoints skip authorization checks because the developer assumed the frontend would handle access control. Rate limiters never get implemented because the product team never filed a ticket for them. Internal APIs end up on the public internet because a load balancer configuration changed and nobody audited the exposure. These are not hypothetical scenarios. Each one maps to a real breach that cost real money.

What That Negligence Actually Costs

In September 2022, Optus, Australia’s second-largest telecom, discovered that an unauthenticated API endpoint was sitting on the public internet. No API key. No OAuth token. No authentication of any kind. An attacker queried it with sequential customer identifiers and pulled out 9.8 million customer records, including names, dates of birth, passport numbers, and driver’s license details. The entire breach happened because a single API endpoint had no authentication layer. Optus faced regulatory investigations, class-action lawsuits, and an estimated remediation cost exceeding $140 million.

That same year, T-Mobile disclosed that an attacker had been quietly extracting data through one of their APIs for six weeks before anyone noticed. The API itself was authorized. The attacker had valid credentials. But no monitoring system flagged that a single caller was pulling 37 million customer records at a pace that no legitimate use case would explain. The API worked exactly as designed. The problem was that nobody designed for the scenario where a valid caller turns malicious.

Facebook’s Contact Importer API had no meaningful rate limiting on phone number lookups. Attackers enumerated phone numbers sequentially and matched them to user profiles. By the time Facebook patched the vulnerability in 2019, scrapers had already collected 533 million user records across 106 countries. The dataset surfaced on hacking forums in April 2021 and remains freely available today. APIs now account for over 71% of web traffic according to Cloudflare’s API security research. Every one of those API calls is a potential attack vector.

Free to use, share it in your presentations, blogs, or learning materials.
Developer view vs attacker view of an API showing six attack vectors including BOLA, broken auth, injection, data leak, rate limiting, and shadow APIs
A developer sees a clean request flow. An attacker sees six entry points to probe.

The left side shows how most developers think about their API: a simple pipeline from request to response. The right side shows what an attacker actually targets. Every arrow represents a class of vulnerability that has caused a real, documented breach.

Authentication Done Right

Authentication is the first gate. If this gate fails, nothing else matters. The choice of authentication mechanism depends on the use case, but three approaches dominate modern API development: OAuth 2.0 with OpenID Connect for user-facing APIs, API keys for server-to-server calls, and JSON Web Tokens for stateless authentication in distributed systems.

OAuth 2.0 and Token Handling

OAuth 2.0 remains the standard for delegated authorization. Over 95% of public-facing APIs from Google, Microsoft, Stripe, and GitHub use it. The OAuth 2.1 draft specification consolidates years of lessons by requiring PKCE (Proof Key for Code Exchange) for all clients and banning the implicit flow entirely. If your API still supports the implicit grant, it is time to migrate.

Access tokens should have short lifetimes. Fifteen minutes is a reasonable starting point for user-facing APIs. Refresh tokens provide continuity without the risk of a long-lived access token sitting in a compromised client. Store refresh tokens securely on the server side, rotate them on every use, and invalidate the entire token family if a refresh token is reused (which indicates theft).

JSONToken lifetime configuration example (OAuth 2.0 server)
1{
2  “access_token_lifetime”: 900,
3  “refresh_token_lifetime”: 604800,
4  “refresh_token_rotation”: true,
5  “refresh_token_reuse_detection”: true,
6  “token_signing_algorithm”: “RS256”,
7  “issuer”: “https://auth.example.com”,
8  “audience”: [“https://api.example.com”]
9}

Every field in that configuration exists because someone got it wrong. The refresh_token_reuse_detection flag triggers automatic invalidation when a stolen refresh token is replayed. Without it, an attacker who intercepts a refresh token can maintain access indefinitely, even after the legitimate user’s session ends.

JWT Pitfalls That Cause Real Breaches

JSON Web Tokens are everywhere, and they are frequently misconfigured. The most dangerous mistake is accepting the alg: "none" header, which tells the server to skip signature verification entirely. An attacker modifies the token payload, sets the algorithm to “none”, removes the signature, and the server accepts it as valid. In January 2023, Auth0 disclosed CVE-2022-23529, where a malicious JWT could trigger arbitrary code execution during the verification process itself. The vulnerability existed in one of the most widely used JWT libraries.

Another common mistake is algorithm confusion. If your server uses RS256 (asymmetric, with a private/public key pair) but an attacker sends a token signed with HS256 (symmetric) using the public key as the HMAC secret, some libraries will accept it. The fix is to enforce the expected algorithm on the server side, never letting the token dictate how it should be verified.

PythonVerify JWT with enforced algorithm (PyJWT)
 1import jwt
 2
 3# Always specify the expected algorithm. Never let the token choose
 4decoded = jwt.decode(
 5    token,
 6    public_key,
 7    algorithms=[“RS256″],       # Reject HS256, none, and everything else
 8    audience=”https://api.example.com”,
 9    issuer=”https://auth.example.com”
10)

Beyond algorithm enforcement, validate every claim: exp (expiration), iss (issuer), aud (audience), and nbf (not before). A token without an audience claim can be replayed against any service that shares the same signing key. A token without an issuer check can be forged by any party with access to a valid signing key from a different service.

API Keys: The Credential That Gets Committed to Git

API keys are the simplest authentication mechanism and the most frequently leaked. In March 2022, the Lapsus$ group breached Samsung’s source code repositories and found embedded API keys, authentication tokens, and private keys scattered across 190 GB of stolen code. Travis CI exposed authentication tokens for tens of thousands of open-source projects through an improperly secured API endpoint in 2021. The tokens included credentials for GitHub, AWS, and Docker Hub.

If your system uses API keys, treat them like passwords. Store them in a secrets manager (AWS Secrets Manager, HashiCorp Vault, or Google Secret Manager), never in source code or environment files committed to version control. Rotate them on a defined schedule. Scope them to the minimum required permissions. And monitor their usage patterns so you can detect when a key is being used from an unexpected location or at an unusual volume.

Authorization: The Vulnerability Developers Keep Missing

Broken Object Level Authorization (BOLA) is the number one vulnerability in the OWASP API Security Top 10 (2023). It accounts for roughly 40% of all API attacks. The pattern is simple: an API accepts a resource identifier from the client, fetches the resource, and returns it without checking whether the authenticated user has permission to access it.

In 2021, security researcher Jan Masters discovered that Peloton’s API endpoints returned user profile data for any user ID without verifying the caller’s identity. Age, gender, city, weight, and workout history for approximately 3 million users were accessible to anyone who could guess or enumerate user IDs. The API checked whether a request was authenticated but never checked whether the authenticated user was authorized to view the requested profile.

The USPS Informed Visibility API had an identical problem. Any authenticated user could query any other user’s data by swapping account parameters in the request. Wildcard search parameters made mass enumeration even easier. The breach exposed 60 million user records including street addresses, email addresses, and phone numbers. The fix for BOLA is conceptually simple but operationally difficult: every single endpoint that accesses a resource must verify that the authenticated caller owns or has explicit permission to access that specific resource.

PythonAuthorization check on every resource access (Flask)
 1@app.route(“/api/v1/orders/<order_id>“, methods=[“GET”])
 2@require_auth
 3def get_order(order_id):
 4    order = Order.query.get_or_404(order_id)
 5
 6    # This single line prevents BOLA. Never skip it
 7    if order.user_id != g.current_user.id:
 8        abort(403)
 9
10    return jsonify(order.to_dict())

That three-line authorization check is the difference between a secure endpoint and a breach. The problem is scale. A typical API has dozens or hundreds of endpoints. Each one needs this check, and it needs to be correct for the specific resource being accessed. One missed endpoint is enough. Middleware-based authorization (where a decorator or interceptor enforces ownership checks before the handler runs) reduces the risk of individual endpoints being missed.

Mass Assignment: The Fields Your API Should Not Accept

OWASP API3:2023 (Broken Object Property Level Authorization) covers a related but distinct problem. It happens when an API accepts more fields than it should in a request body. A user update endpoint that accepts {"name": "Alice", "role": "admin"} and blindly writes all fields to the database just gave the caller admin privileges. The API exposed a writable property that should have been read-only.

The fix is explicit allowlisting. Define exactly which fields each endpoint accepts, and discard everything else. In frameworks like Django REST Framework, this means setting fields or read_only_fields on serializers. In Express.js, it means destructuring only the expected properties from req.body instead of passing the entire object to the database.

JavaScriptExplicit field allowlisting (Express.js)
 1app.put(“/api/v1/users/:id”, authenticate, async (req, res) => {
 2  // Only accept fields the user is allowed to modify
 3  const { name, email, timezone } = req.body;
 4
 5  // role, is_admin, account_tier: silently discarded
 6  await User.update(
 7    { name, email, timezone },
 8    { where: { id: req.params.id } }
 9  );
10
11  res.json({ status: “updated” });
12});

Input Validation Beyond “Check If It’s a String”

Input validation is the practice most developers think they do well, right until a security audit proves otherwise. Checking whether a field is a string is not validation. Validation means enforcing the exact shape, size, type, and range of every value your API accepts. The OpenAPI Specification (OAS) 3.1 provides a machine-readable format for defining these constraints, and middleware can enforce them automatically before your handler code ever runs.

Schema validation catches malformed requests at the gate. If your endpoint expects a JSON object with a quantity integer between 1 and 1000, the schema rejects a quantity of negative five million before your application logic has to deal with it. Type confusion vulnerabilities occur when an API interprets a string as a command or a number as an array index. Strict schema enforcement eliminates entire categories of these bugs.

YAMLOpenAPI schema with strict validation rules
 1paths:
 2  /api/v1/orders:
 3    post:
 4      requestBody:
 5        required: true
 6        content:
 7          application/json:
 8            schema:
 9              type: object
10              required: [product_id, quantity, shipping_address]
11              additionalProperties: false
12              properties:
13                product_id:
14                  type: string
15                  pattern: “^[a-zA-Z0-9]{8,24}$”
16                quantity:
17                  type: integer
18                  minimum: 1
19                  maximum: 1000
20                shipping_address:
21                  type: string
22                  maxLength: 500
23                  minLength: 10

The additionalProperties: false setting is critical. Without it, a caller can inject arbitrary fields into the request body. Combined with the mass assignment vulnerability described above, this turns input validation into a backdoor. Set it to false on every request schema.

Beyond structural validation, enforce business logic constraints. A date of birth in the year 2085 might pass a date type check but makes no sense for a user registration endpoint. A shipping address of “‘; DROP TABLE orders;–” might pass a string check but should trigger injection detection. Layer your validation: schema first, then business rules, then sanitization for output encoding if any user-supplied content will be rendered in a browser.

Rate Limiting: The Control Nobody Implements Until It’s Too Late

Rate limiting is the simplest security control to understand and one of the most commonly skipped. The logic is straightforward: limit how many requests a caller can make in a given time window. Without it, your API is open to brute force attacks, credential stuffing, data scraping, and denial of service.

Facebook’s Contact Importer API had no meaningful rate limiting. Attackers queried phone numbers sequentially, matching each one to a user profile. The result was 533 million records scraped across 106 countries. LinkedIn’s profile API had the same problem. Scrapers paged through results systematically, collecting 700 million user records that were later sold on hacking forums. Parler’s API went even further: sequential post IDs, zero authentication, and zero rate limiting allowed the entire platform (over 70 TB of data including GPS-tagged videos) to be downloaded before AWS terminated their hosting.

Implement rate limits at multiple levels. Per-user limits prevent a single compromised account from scraping your entire dataset. Per-IP limits slow down distributed attacks. Per-endpoint limits protect sensitive operations like login, password reset, and payment processing with stricter thresholds than read-only endpoints.

PHPRate limiting configuration (nginx example)
 1# Global: 100 requests per second per IP
 2limit_req_zone $binary_remote_addr zone=global:10m rate=100r/s;
 3
 4# Login: 5 requests per minute per IP (strict)
 5limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
 6
 7# API: 30 requests per second per authenticated user
 8limit_req_zone $http_authorization zone=api_user:10m rate=30r/s;
 9
10server {
11    location /api/v1/auth/login {
12        limit_req zone=login burst=3 nodelay;
13        limit_req_status 429;
14        proxy_pass http://backend;
15    }
16
17    location /api/v1/ {
18        limit_req zone=api_user burst=10 nodelay;
19        limit_req zone=global burst=20 nodelay;
20        limit_req_status 429;
21        proxy_pass http://backend;
22    }
23}

Return proper HTTP headers so legitimate clients can adapt their behavior. The X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers tell callers exactly where they stand. Respond with 429 Too Many Requests when limits are exceeded, and include a Retry-After header. Callers that respect these headers get a better experience. Callers that ignore them get blocked, which is exactly the point.

Logging and Monitoring: Catching Breaches Before They Escalate

T-Mobile’s 2023 breach is the textbook case for why API monitoring matters. An attacker used valid API credentials to extract 37 million customer records over six weeks. The API was functioning correctly. Authentication was working. Authorization was passing. But the volume of data extraction was orders of magnitude beyond any legitimate use pattern, and no monitoring system flagged it.

Security monitoring for APIs needs to go beyond uptime checks and error rates. It needs to detect behavioral anomalies: a single API key pulling 50,000 records in an hour when the normal pattern is 200 per day. A user account accessing 10,000 different customer profiles when their role should only access their own. A burst of 401 errors from a single IP followed by a successful 200 response (which indicates credential stuffing that found a valid password).

Log every authentication event, every authorization failure, every input validation rejection, and every rate limit violation. Feed these logs into a SIEM platform (Splunk, Elastic Security, or Datadog Security Monitoring) with alerting rules tuned to API-specific attack patterns. Set up alerts for: sudden spikes in 4xx errors from a single source, sequential resource ID access patterns (which indicate enumeration), and any access to deprecated or undocumented endpoints.

Equally important is what you do not log. Passwords, tokens, credit card numbers, and personally identifiable information must be masked or excluded from logs entirely. A security log that contains plaintext credentials becomes a liability rather than an asset. Use structured logging with explicit field definitions so sensitive data cannot accidentally leak into log entries.

PythonStructured API security logging
 1import structlog
 2
 3logger = structlog.get_logger()
 4
 5def log_api_request(request, response, user):
 6    logger.info(
 7        “api_request”,
 8        method=request.method,
 9        path=request.path,
10        status=response.status_code,
11        user_id=user.id if user else “anonymous”,
12        ip=request.remote_addr,
13        # Never log: tokens, passwords, request bodies with PII
14        response_time_ms=response.elapsed_ms,
15        rate_limit_remaining=response.headers.get(“X-RateLimit-Remaining”),
16    )
17
18def log_auth_failure(request, reason):
19    logger.warning(
20        “auth_failure”,
21        path=request.path,
22        ip=request.remote_addr,
23        reason=reason,    # “invalid_token”, “expired”, “wrong_audience”
24        user_agent=request.headers.get(“User-Agent”, “”),
25    )

API Inventory and the Shadow API Problem

Gartner predicted that by 2025, less than 50% of enterprise APIs would be managed. The reality may be worse. Shadow APIs are endpoints that exist in production but do not appear in any documentation, any API gateway configuration, or any security scan. They include test endpoints that were never removed, deprecated versions that still respond to requests, and internal services that were accidentally exposed through a misconfigured load balancer.

Optus’s breach came through exactly this kind of endpoint. The exposed API was likely a test or internal endpoint that should never have been reachable from the public internet. In August 2021, researchers at UpGuard discovered that Microsoft Power Apps OData APIs were configured by default to allow anonymous access. Across 47 organizations, including state governments and American Airlines, 38 million records were exposed because the default API configuration did not require authentication. Microsoft subsequently changed the default to require authentication, but the damage was done. Default configurations should always be secure. If an administrator has to take action to make an API safe, some of them will not.

Maintaining an accurate API inventory is not optional. Every API endpoint in production should be documented, registered in your API gateway, and included in security scans. Run periodic discovery scans using tools like Kiterunner or API-specific scanners to find endpoints that do not match your documentation. When you deprecate an API version, shut it down. Do not leave it running because “some old client might still use it.” That old client is also an attacker’s entry point.

Securing the API Gateway Layer

An API gateway is the single chokepoint through which all API traffic should flow. Over 90% of organizations with API programs use some form of gateway, whether it is Kong, Amazon API Gateway, Azure API Management, or Google Apigee. The gateway handles the cross-cutting concerns that should not live in individual service code: TLS termination, authentication, rate limiting, request validation, and logging.

Enforce HTTPS for all API communication without exception. HTTP Strict Transport Security (HSTS) headers prevent downgrade attacks where an attacker forces a client to fall back to unencrypted HTTP. For service-to-service communication within your infrastructure, mutual TLS (mTLS) provides both encryption and identity verification. Service mesh platforms like Istio and Linkerd automate mTLS between services in Kubernetes clusters.

YAMLAPI gateway security headers
1# Response headers every API should return
2Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
3Content-Type: application/json; charset=utf-8
4X-Content-Type-Options: nosniff
5X-Frame-Options: DENY
6Cache-Control: no-store
7X-RateLimit-Limit: 100
8X-RateLimit-Remaining: 87
9X-RateLimit-Reset: 1713234567

Configure the gateway to reject requests that fail schema validation before they reach your application servers. This offloads a significant amount of malicious traffic processing from your backend. A request with an invalid content type, an oversized body, or a malformed JSON payload should never touch your application code. The gateway should return a 400 Bad Request before the request is proxied.

Free to use, share it in your presentations, blogs, or learning materials.
API security layers diagram showing request flow from client through TLS, API gateway, application logic, monitoring, to database with attack types stopped at each layer
Each layer in the API request journey stops a different category of attack. Skipping any layer creates a gap that attackers will find.

The diagram above shows why defense in depth matters for APIs. TLS stops eavesdropping. The gateway stops brute force and invalid tokens. Application logic stops BOLA and privilege escalation. Monitoring catches slow exfiltration. The database layer stops injection. Remove any single layer, and an entire class of attacks gets through.

Building Security Into the Development Workflow

API security cannot be a phase that happens after development. It must be integrated into every stage of the workflow. The cost of fixing a vulnerability increases by roughly 30x as it moves from design to production, according to IBM’s Systems Sciences Institute research. A BOLA vulnerability caught during code review costs a developer 30 minutes to fix. The same vulnerability discovered through a breach costs millions in incident response, legal fees, regulatory fines, and customer trust.

Threat modeling during API design is the cheapest security investment you can make. Before writing code, ask: who can call this endpoint? What resource does it access? Does the caller need to prove they own that resource? What happens if someone calls it 10,000 times? What fields does it return, and should any of them be filtered for certain callers? These questions take 15 minutes to answer during design and 15 days to remediate in production.

In the CI/CD pipeline, run automated API security scans on every pull request. Tools like 42Crunch audit OpenAPI specifications for security misconfigurations. OWASP ZAP and Burp Suite can run automated DAST (Dynamic Application Security Testing) scans against staging environments. For runtime protection in production, platforms like Salt Security and Traceable AI monitor live API traffic for attack patterns and behavioral anomalies.

  • Design phase. Threat model every endpoint. Define authentication, authorization, and rate limiting requirements before writing code
  • Development phase. Write OpenAPI specs with strict schemas. Use security-focused code review checklists that include BOLA, mass assignment, and injection checks
  • CI/CD pipeline. Automated spec auditing (42Crunch), SAST scans for hardcoded secrets (GitLeaks, TruffleHog), and DAST scans against staging
  • Production. API gateway enforcement, runtime anomaly detection, structured security logging with SIEM alerting, and periodic penetration testing

The OWASP API Security Top 10 (2023) Mapped to Real Breaches

The OWASP API Security Top 10 was updated in June 2023, replacing the 2019 edition with four new entries. Each vulnerability maps directly to a breach covered in this article. Understanding the pattern helps you recognize these vulnerabilities in your own APIs before an attacker does.

Free to use, share it in your presentations, blogs, or learning materials.
OWASP API Security Top 10 2023 mapped to real breaches including Peloton, Optus, Facebook, Uber, and Power Apps incidents
Every entry in the OWASP API Security Top 10 (2023) maps to at least one documented breach. The patterns repeat across industries.

Here is each entry with the breach that brought it to life:

API1:2023 Broken Object Level Authorization. The attacker substitutes a resource ID in the request to access another user’s data. Peloton (3 million user profiles, 2021), USPS (60 million records, 2018), and Twitter (200 million email-to-handle mappings, 2022) all fell to this exact pattern. The fix: verify resource ownership on every endpoint.

API2:2023 Broken Authentication. Weak or missing authentication allows unauthenticated access. Optus (9.8 million records, no auth required, 2022) and Experian Brazil (220 million records, internal API with no auth, 2021) are the clearest examples. The fix: enforce authentication on every endpoint, including internal ones.

API3:2023 Broken Object Property Level Authorization. The API returns more data than the caller should see or accepts fields that should be read-only. This merged two items from the 2019 list (Excessive Data Exposure and Mass Assignment). The fix: explicit field allowlisting on both input and output.

API4:2023 Unrestricted Resource Consumption. No rate limiting, no request size limits, no pagination caps. Facebook (533 million records scraped via sequential phone lookups, 2021), LinkedIn (700 million profiles scraped, 2021), and Parler (70 TB of data downloaded, 2021) all resulted from this. The fix: rate limits at every layer.

API5:2023 Broken Function Level Authorization. A regular user accesses administrative endpoints because the API only enforces role checks on the frontend. The fix: server-side role verification on every endpoint, regardless of what the client does.

API6:2023 Unrestricted Access to Sensitive Business Flows. New in 2023. APIs expose business operations (purchasing, account creation, posting) without protection against automated abuse. Scalper bots, credential stuffing, and automated spam all exploit this. The fix: CAPTCHA, device fingerprinting, and behavioral analysis on sensitive flows.

API7:2023 Server Side Request Forgery (SSRF). New in 2023. The API fetches a remote resource based on a user-supplied URL without validation, allowing attackers to scan internal networks or access cloud metadata endpoints. The fix: validate and allowlist all URLs before fetching.

API8:2023 Security Misconfiguration. Missing TLS, verbose error messages exposing stack traces, unnecessary HTTP methods enabled, missing CORS restrictions. Microsoft Power Apps (38 million records, default anonymous access, 2021) is a direct example. The fix: secure defaults and configuration auditing.

API9:2023 Improper Inventory Management. Deprecated API versions still running, undocumented shadow APIs, unpatched endpoints. The fix: maintain an accurate, automated API inventory and shut down anything not in it.

API10:2023 Unsafe Consumption of APIs. New in 2023. Your API consumes data from a third-party API without validating it, allowing attackers to compromise your system through the upstream service. The fix: treat third-party API responses with the same skepticism as user input.


References


Frequently Asked Questions

What is the most common API security vulnerability?

Broken Object Level Authorization (BOLA) is the most common API vulnerability, accounting for roughly 40% of all API attacks according to OWASP and Salt Security data. It occurs when an API endpoint accepts a resource identifier from the caller and returns the resource without verifying ownership. Peloton, USPS, and Twitter all suffered breaches through this exact vulnerability pattern.

Should I use API keys or OAuth 2.0 for my API?

Use OAuth 2.0 with OpenID Connect for user-facing APIs where delegated authorization and granular scopes are needed. Use API keys only for simple server-to-server integrations where the calling service is trusted and the communication channel is secure. Never use API keys as the sole authentication mechanism for public-facing endpoints. Over 95% of major public APIs (Google, Stripe, GitHub) use OAuth 2.0.

What rate limits should I set for my API?

Rate limits depend on your endpoint type and expected usage. A common baseline is 100 requests per minute for general endpoints and 5 requests per minute for authentication endpoints (login, password reset). For data-heavy endpoints, limit by both request count and data volume. Always implement limits at multiple levels: per-user, per-IP, and per-endpoint. Monitor actual usage patterns for 2 weeks before tightening limits.

How do I prevent JWT token forgery in my API?

Enforce the expected signing algorithm on the server side (never let the token header dictate the algorithm). Reject tokens with alg:none. Always validate the exp, iss, aud, and nbf claims on every request. Use RS256 (asymmetric) over HS256 (symmetric) for public-facing APIs so the signing key stays server-side. Keep access token lifetimes under 15 minutes and use rotating refresh tokens for longer sessions.

How much does an API security breach cost on average?

API-related breaches cost between $4.1 million and $6.1 million on average, above the general data breach average of $4.45 million reported by IBM’s 2023 Cost of a Data Breach study. The actual cost varies by industry and breach size. Optus’s 2022 breach through a single unauthenticated API endpoint resulted in estimated remediation costs exceeding $140 million, including regulatory fines, legal settlements, and customer notification costs.

What are shadow APIs and why are they dangerous?

Shadow APIs are endpoints running in production that do not appear in any documentation, API gateway, or security scan. They include test endpoints that were never removed, deprecated versions that still accept traffic, and internal services accidentally exposed through misconfigured infrastructure. Gartner estimates that less than 50% of enterprise APIs are managed. Optus’s 2022 breach came through an unauthenticated endpoint that should not have been reachable from the public internet.

What tools can I use to test my API security?

For specification auditing, 42Crunch scans OpenAPI specs for misconfigurations. For dynamic testing, OWASP ZAP and Burp Suite run automated scans against live endpoints. For secret detection in code, GitLeaks and TruffleHog scan repositories for hardcoded API keys and tokens. For runtime protection in production, Salt Security and Traceable AI monitor live API traffic for behavioral anomalies. Run spec audits in CI/CD pipelines and dynamic scans against staging environments before every release.