What Is API Security?

API security is the discipline of protecting Application Programming Interfaces (the interfaces through which software systems communicate) from unauthorized access, data exposure, abuse, and exploitation.

Because APIs are designed to expose functionality and data efficiently, they present an inherently large and systematically exploitable attack surface: attackers can probe, enumerate, and automate attacks against APIs at scales that manual web-browsing attacks cannot achieve.

API security encompasses authentication and authorization controls, input validation, rate limiting, traffic monitoring, and design patterns that prevent the most common vulnerability classes, particularly broken object-level authorization - the failure to verify that a requesting user is entitled to access the specific data object they are requesting.

In 2018, researchers revealed a vulnerability in the US Postal Service's Informed Visibility API. What was wrong with the API was simple. It did not properly check that users had access only to their own account data.

Anyone logged in with a regular USPS.com account could pass another person's account ID to the API and pull back their name, street address, phone number and email address, putting roughly 60 million users at risk.

The vulnerability had been present for over a year before disclosure.

The USPS incident is not unusual. It represents the single most common class of API security failure: an interface that was built to expose data efficiently but was not designed to enforce who can access which data.

The same fundamental error has appeared in breaches at Venmo, Instagram, Facebook, LinkedIn, T-Mobile, Peloton and hundreds of lesser-known services. The names change but the vulnerability class is the same.

APIs have become the dominant architecture for modern software. Mobile apps, web applications, microservices, IoT devices and third-party integrations all communicate primarily through APIs.

API security is no longer a niche concern for security specialists. It has become a fundamental responsibility for every developer and architect who works on modern software.

Gartner predicted as early as 2022 that API abuse would become the most frequent attack vector for enterprise web application breaches.[4]


The Scale of the API Attack Surface

APIs represent the fastest-growing attack surface in enterprise computing. In 2024, 95% of organizations surveyed had experienced an API security incident in the prior twelve months - up from 94% in 2023.[2]

The same report found that the volume of API attacks had increased by 167% year over year.

The scale of API exposure is hard to overstate. Akamai, which operates one of the largest content delivery networks, reported in 2023 that over 83% of web traffic it processed was API traffic.[3]

Organizations typically have far more APIs than they have documented: the Salt Security report found organizations had an average of 3x more APIs in production than they believed when measured against internal documentation.

"The challenge with API security is not just that APIs are attacked - it is that most organizations do not have complete visibility into what APIs they have exposed, which makes it impossible to know what to protect."

Salt Security, State of API Security Report 2024

What an API Is and Why It Creates Security Challenges

An Application Programming Interface (API) is a defined set of rules that allows one piece of software to communicate with another. When your weather app retrieves the current temperature, it calls a weather service API. When you log in with Google, an OAuth API handles the authentication flow.

When a payment processes on an e-commerce site, a Stripe or PayPal API is being called.

REST APIs (Representational State Transfer) are the most common pattern for web and mobile applications: they use standard HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources identified by URLs.

GraphQL APIs let clients say precisely what data they want in a flexible query format that brings extra security work on query complexity as well as depth limits. Internal service-to-service communication can use gRPC and other patterns.

Webhooks allow services to push notifications to external endpoints. This creates a different attack surface around endpoint verification.

The security challenge with APIs is inherent to their purpose. They are designed to expose functionality and data. A well-designed API is accessible, predictable and machine-readable. That means attackers can probe, enumerate and exploit it programmatically at scale in ways that manual web browsing does not allow.

API-specific threats include:

  • Automated enumeration: attackers can iterate through thousands of object IDs systematically
  • Machine-speed credential attacks: automated password guessing at volumes impossible via web forms
  • Schema inference: the predictable structure of APIs allows attackers to understand the data model
  • Endpoint discovery: documentation, JavaScript bundles, and network traffic can reveal undocumented endpoints
  • Privilege escalation: APIs that expose different data based on permissions must enforce those permissions consistently on every request
  • Data harvesting: APIs designed for single-record queries can be systematically scraped to harvest entire datasets

The OWASP API Security Top 10

Ranking the most critical API security risks, the Open Web Application Security Project (OWASP) puts out its API Security Top 10. The 2023 edition brings in major changes from the original 2019 list as it reflects how the API threat landscape has evolved.[1]

RankVulnerabilityCore Problem
API1Broken Object Level AuthorizationAPI accepts object IDs but does not verify access rights to those objects
API2Broken AuthenticationWeak or missing authentication mechanisms allow account takeover
API3Broken Object Property Level AuthorizationAPI exposes or allows modification of sensitive object properties
API4Unrestricted Resource ConsumptionNo rate limiting; DoS or financial damage via excessive requests
API5Broken Function Level AuthorizationUsers can call administrative or privileged functions they should not access
API6Unrestricted Access to Sensitive Business FlowsBots can abuse business flows (ticket purchasing, account creation) at scale
API7Server Side Request ForgeryAPI can be made to request internal resources on behalf of attacker
API8Security MisconfigurationDefault credentials, verbose error messages, unnecessary HTTP methods enabled
API9Improper Inventory ManagementOutdated or undocumented API versions and endpoints remain accessible
API10Unsafe Consumption of APIsThe application blindly trusts third-party API responses without validation

API1: Broken Object Level Authorization (BOLA)

Also known as Insecure Direct Object Reference or IDOR in web app contexts, BOLA is by far the most common and most impactful API vulnerability. The incident at USPS above is a textbook BOLA vulnerability. The pattern is simple.

GET /api/orders/10234   -> returns your order  (correct)
GET /api/orders/10235   -> returns someone else's order  (BOLA vulnerability)

The API takes the object ID from the request but the authorization check only confirms that the user is logged in and does not check whether this particular user has permission to access object 10235.

This error appears at scale partly because authorization is often added late in development, inconsistently across endpoints, or left to the API client to enforce (which provides zero protection).

Correct implementation. With each request, permission checks ask whether this authenticated user has the right to carry out this operation on that particular object. These checks must take place in the business logic layer on every call and they cannot occur only at route level or login time.

A documented real-world example beyond USPS: in 2019, Venmo's API allowed any user to query public transaction data from any other user, including financial transaction descriptions. A developer scraped and published 7 million transactions to illustrate the privacy implications.

Venmo addressed the default public setting but the underlying API had no access controls at the object level for users who chose to keep data public.

API2: Broken Authentication

Authentication vulnerabilities in APIs include:

  • Weak passwords accepted with no minimum complexity enforcement
  • No credential stuffing protection: the API allows unlimited password attempts
  • Insecure token handling: tokens transmitted in URLs (logged in server logs, browser history, referrer headers), not expiring, or not invalidated on logout
  • Weak token algorithms: JWT tokens signed with HS256 using weak secrets that can be brute-forced; JWT tokens with alg: none accepted
  • Missing multi-factor authentication for sensitive operations
  • Predictable token generation: tokens based on timestamps, sequential IDs, or weak random number generators

API5: Broken Function Level Authorization

In the API world, BFLA is privilege escalation: an ordinary user manages to call admin-only endpoints. That usually happens when teams build and document routes without applying permission checks evenly across them or when they leave admin routes out of the docs while leaving them wide open on the server.

DELETE /api/admin/users/12345   -> should require admin role
                                -> actually accepts any authenticated token

Attackers can discover the pattern easily by looking at API documentation, examining JavaScript bundles or monitoring network traffic during normal use to find out which endpoint patterns exist and then testing whether privileged endpoints need authorization.

Automated tools specifically designed for API reconnaissance make this process rapid.

API6: Unrestricted Access to Sensitive Business Flows

Added in 2023, this category covers a class of attacks that go after business logic instead of authentication or authorization controls. The examples that follow are included in it.

  • Automated ticket-buying bots that purchase all available inventory before legitimate buyers
  • Account creation bots that generate thousands of accounts to exploit per-user promotions
  • Automated review submission systems that generate fake reviews at scale
  • Price scraping that violates competitive intelligence policies

These attacks work by using valid credentials and sending requests that are each individually valid. Without behavioral analysis, they are hard to tell apart from legitimate traffic.


Authentication: OAuth 2.0, JWT, and API Keys

Authentication - proving who is making a request - is the foundation of API security. The right authentication mechanism depends on the use case.

API Keys

API keys are simple shared secrets most often long random strings that go in request headers or query parameters. The keys fit server-to-server communication when both sides are under the same organization's control or they work for public APIs where the key identifies the client application and not the user.

API key security requirements:

  • Sufficient entropy (minimum 32 bytes of randomness, generating a 256-bit key)
  • Transmitted only in headers (never in URLs, which are logged in server logs, browser history, and network proxies)
  • Rotatable without disrupting service
  • Revocable individually without affecting other clients
  • Scoped to specific permissions where possible

API keys are routinely leaked by accident. GitHub reported that developers accidentally committed over 10 million secrets to public repositories in 2022 alone.[7]

GitHub's secret scanning tool and others like it take care of part of this problem. Secret scanning is the one that now automatically revokes detected credentials for major providers.

JWT (JSON Web Token)

JWTs have a self-contained token format that puts claims (who you are, what you can do, when the token expires) in a JSON object and signs it cryptographically. They let the server check a JWT without a database query and that makes them efficient for stateless authentication.

A JWT consists of three base64-encoded parts separated by dots: header.payload.signature

The payload is base64-encoded but not encrypted - it is trivially readable by anyone who holds the token. This is an important property: sensitive data must never be placed in a JWT payload.

Common JWT vulnerabilities to avoid:

VulnerabilityDescriptionPrevention
Algorithm confusionalg: none attack; accepting unsigned tokensExplicitly configure accepted algorithms; never accept none
Weak secretHS256 secrets short enough to brute-forceUse 256+ bit secrets; prefer RS256 for public verification
No expirationTokens valid indefinitelyAlways set exp claim; use short-lived access tokens (15-60 min)
No revocationStolen tokens remain valid until expiryImplement token blocklist or use short expiry with refresh tokens
Sensitive data in payloadPayload is base64-encoded, not encryptedNever store sensitive data in JWT payload (it is readable)
Signature not verifiedLibrary bug or misconfiguration accepts any signatureUse well-maintained libraries; test signature verification explicitly

The alg: none vulnerability, discovered by Tim McLean in 2015, is a stark example of how JWT can be misimplemented: if a library trusts the algorithm specified in the JWT header, an attacker can set alg: none, remove the signature, and forge any claims.[5]

This bug was present in multiple JWT libraries and illustrates why JWT security depends heavily on correct implementation rather than just choosing the standard.

OAuth 2.0

OAuth 2.0 is the industry-standard authorization framework for third-party delegation. It lets one app act on a user's behalf on another service without sharing passwords. It defines several flows for different contexts.

  • Authorization Code Flow (for web apps): most secure; exchanges a short-lived authorization code for tokens
  • PKCE (Proof Key for Code Exchange): extension of Authorization Code for mobile and SPAs; prevents code interception attacks
  • Client Credentials Flow: for machine-to-machine communication without user involvement
  • Device Authorization Flow: for input-constrained devices (smart TVs, IoT)

Any client-side or mobile app should use the Authorization Code Flow with PKCE. The Implicit Flow that sends tokens straight to the browser has been deprecated and new apps should not use it.

Real attacks show why the Implicit Flow is being deprecated (RFC 9700, January 2025 and also OAuth 2.1 draft). Access tokens in URLs can get out through browser history, referrer headers and server logs. The code interception attack that drove the use of Implicit Flow is eliminated by PKCE.[6]


Rate Limiting and Throttling

APIs without rate limiting are vulnerable to:

  • Denial of service: excessive legitimate or malicious requests overwhelming the server
  • Credential stuffing: automated testing of stolen username/password pairs at scale
  • Data scraping: programmatic bulk extraction of publicly accessible data
  • Resource exhaustion. Calls that are expensive operations such as database queries, file processing and AI inference thousands of times a minute
  • Account enumeration: systematically testing whether email addresses exist in a system

Effective rate limiting implementation:

Limit by client identity, not just by IP address. Rate limiting based on IP address can be got around via proxies, rotating residential proxies and distributed botnets. When rate limiting by API key or user ID, it is much harder to get around.

Apply limits per endpoint, calibrated to the cost of that endpoint. A simple read endpoint might allow 1,000 requests per minute; a password reset endpoint should allow perhaps 5 per hour per account; an AI-powered search might allow 10 per minute.

Return appropriate HTTP responses: HTTP 429 Too Many Requests with a Retry-After header telling legitimate clients when they can retry. This allows well-behaved clients to back off gracefully without breaking their functionality.

Implement progressive delays for authentication failures. After N failed attempts, require exponentially increasing wait times or CAPTCHA challenges. AWS Cognito, Auth0 and other identity providers implement this by default.

Log rate limit events. Security monitoring gets a strong signal of automated attack activity when a single IP or user generates a burst of 429 responses.


Input Validation

Every API endpoint that accepts data must validate that data before processing it. Input validation failures remain one of the most common sources of API vulnerabilities, ranging from injection attacks to business logic errors.

What to Validate

For every input field:

  • Type: is this a string, integer, UUID, email address, date?
  • Format: does a date field contain a valid date? Does a UUID match the UUID format?
  • Length: is the string within acceptable bounds?
  • Range: is the integer within expected values?
  • Allowed values: if the field should be one of a fixed set, validate against that set
  • Presence: is a required field present?
  • Encoding: is the content properly encoded for its type?

Reject unknown fields rather than ignoring them. If your API accepts a user object with name and email, and a request includes an additional role field, the API should return an error rather than silently discarding the unknown field - the intent may be parameter injection.

Injection Prevention

Weak input validation is what makes SQL injection, NoSQL injection and command injection possible. Injection sat at #1 on the 2017 OWASP Top 10 for web apps and even after moving to #3 in 2021 it remains one of the most damaging flaw categories around.

The primary defenses are:

  • Parameterized queries (never concatenate user input into query strings)
  • Input allowlisting (accept only known-good formats, reject everything else)
  • Escaping where parameterization is not available
  • ORM usage with parameterized query generation
# Vulnerable: string concatenation into a query
query = "SELECT * FROM users WHERE id = " + user_input

# Safe: parameterized query
query = "SELECT * FROM users WHERE id = ?"
execute(query, [user_input])

GraphQL-Specific Considerations

Beyond REST, GraphQL APIs come with extra input validation requirements. Because clients can specify any query structure they want, malicious or poorly considered queries can cause:

  • Query depth attacks: deeply nested queries that cause exponential database load
  • Query complexity attacks: queries requesting an enormous number of related records
  • Introspection abuse: querying the schema to discover all available fields and types

GraphQL APIs should implement query depth limits and query complexity analysis. They should also consider disabling introspection in production, though this trades discoverability for security in ways appropriate to the use case.


Common Vulnerabilities in Practice

Mass Assignment

Many API frameworks include features that automatically map request fields to object properties. If not properly configured, this allows attackers to set properties that should not be user-controlled:

POST /api/users/me/update
{
  "name": "Alice",
  "email": "alice@example.com",
  "role": "admin"
}

If the API accepts and applies the role field, even though it was not intended to be user-settable, the user has promoted themselves to admin.

Mass assignment vulnerabilities have appeared in Ruby on Rails, Django, Spring, and virtually every framework that offers automatic request-to-model binding.

The defense is explicit allowlisting of which fields a given endpoint is permitted to update - never binding all request fields automatically.

Excessive Data Exposure

Complete data objects come back from APIs and it is up to the client to filter what gets displayed. Security issues arise when objects hold sensitive fields that should never get out of the server.

GET /api/users/me
{
  "id": "12345",
  "name": "Alice",
  "email": "alice@example.com",
  "password_hash": "$2b$10$...",
  "internal_notes": "flagged user",
  "two_factor_secret": "JBSWY3DPEHPK3PXP"
}

The defense is server-side response filtering. Define exactly what each endpoint returns using serialization schemas or data transfer objects, rather than returning raw database objects.

This must be enforced at the API layer, not left to the client.

Security Misconfigurations

Common API misconfigurations that create vulnerabilities:

  • CORS misconfiguration: allowing all origins (Access-Control-Allow-Origin: *) on endpoints that should be restricted to specific domains
  • HTTP methods not restricted: an endpoint that should be read-only accepting POST, PUT, DELETE
  • Stack traces in error responses: detailed error messages that expose technology stack, database schemas, file paths, or internal IP addresses
  • Default credentials: demo or development credentials left enabled in production
  • Missing HTTPS: API traffic served over plain HTTP; all API traffic must use TLS 1.2 or higher
  • Missing security headers: Content-Security-Policy, X-Content-Type-Options, X-Frame-Options absent

API Security Testing

Every API development lifecycle calls for security testing to be included and it should not be a one-time audit.[11]

Types of Testing

Static analysis. Automated scanning of source code for common vulnerability patterns including injection risks, hardcoded credentials and insecure configurations. The tools are Semgrep, SonarQube and language-specific linters. Today many CI/CD pipelines bring SAST tooling in as a mandatory gate by default.

Dynamic testing: testing the running API by sending crafted requests and analyzing responses. The OWASP ZAP (Zed Attack Proxy) and Burp Suite Professional are widely used tools for API dynamic testing. Burp Suite in particular has extensive API-testing extensions.

Fuzzing. Sending unexpected, malformed or boundary-case inputs helps teams find out how the API deals with them. Automation is available from REST API fuzzers such as RESTler (Microsoft Research) and API-specific modules in Burp Suite.[10] Validation holes and unhandled error conditions frequently appear when the API gets unexpected inputs.

Authorization testing: systematically verifying that every endpoint enforces authorization correctly - that users cannot access objects they do not own (BOLA), cannot call functions at privilege levels they do not hold (BFLA), and cannot modify properties they do not control.

This is the most important and most commonly neglected category.

Penetration testing. This is structured adversarial testing carried out by security professionals. OWASP's API Security Testing Guide gives a full method.[9] Through platforms such as HackerOne and Bugcrowd, bug bounty programs run by companies bring in outside researchers to find actual vulnerabilities.

The API Inventory Problem

Many companies do not even have a full list of their own active APIs. OWASP API9 (Improper Inventory Management) points to a common headache where endpoints multiply across teams, older versions stay live forever and undocumented routes pile up.

There is a large attack surface made up of Shadow APIs. These are endpoints that are technically accessible yet not in the official documentation.

Data from 76.6 million customers was exposed in the T-Mobile 2021 breach and it involved access through an undocumented API endpoint not in the company's known attack surface. Automated reconnaissance is what the attacker used to find it.

An API gateway enforces all traffic to route through a single control point. Combined with automated API discovery tools that scan production traffic, this helps maintain an accurate inventory of what is actually exposed. Tools like Traceable AI, Salt Security and Noname Security specialize in API discovery and behavioral monitoring.


API Security at the Architecture Level

Beyond individual vulnerability prevention, API security requires architecture-level decisions:

API Gateway. A dedicated API gateway (Kong, AWS API Gateway, Azure API Management) centralizes authentication, rate limiting, logging and traffic filtering. It provides a single enforcement point for security policies across all APIs.

Service-to-Service Authentication. Authentication is needed for internal microservice APIs as well. In mutual TLS (mTLS), both client and server show certificates and this gives strong service identity. Service meshes like Istio and Linkerd automate mTLS between services.

Secrets Management: API keys and credentials used by services must be stored securely - not in code, environment variables, or configuration files in source control. Dedicated secrets management tools (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault) provide secure storage, rotation, and audit logging for secrets.

API Versioning and Deprecation. Maintaining multiple API versions without a disciplined deprecation process is a primary cause of API9 (Improper Inventory Management). Version management policies should specify how long old versions are supported, how deprecation is communicated and how decommissioning is enforced.


Summary: API Security Principles

API security is not something to check off once as a list. It is a set of design principles that have to be applied consistently through development and operations.

  1. Authenticate every request - verify identity on every call, not just at login
  2. Authorize every operation - check that this user can perform this action on this object
  3. Validate all input - type, format, length, range; reject everything that does not match
  4. Rate-limit everything - especially authentication, password reset, and resource-expensive endpoints
  5. Return minimal data - expose only what the client needs; never return raw database objects
  6. Log and monitor - security events, rate limit hits, and unusual patterns are only visible if logged
  7. Keep an inventory - know what APIs exist, what versions are deployed, and decommission what is not needed
  8. Test for authorization - automated tests that verify authorization checks are as important as tests that verify functionality
  9. Secure service-to-service communication - internal APIs require authentication; use mTLS or equivalent
  10. Manage secrets properly - store API keys and credentials in dedicated secrets management systems

The attack surface exposed by APIs is real, large and growing. The USPS breach, the T-Mobile breach and hundreds like them demonstrate that the vulnerabilities are not exotic or theoretical.

They are fundamental design errors that are avoidable with consistent application of well-understood principles - applied from the beginning, not added as an afterthought.


Sources

  1. OWASP. (2023). API Security Top 10: 2023. Open Web Application Security Project.
  2. Salt Security. (2024). State of API Security Report Q1 2024. Salt Security Inc.
  3. Akamai Technologies. (2023). State of the Internet: API Security. Akamai.
  4. Gartner. (2022). Gartner Predicts 2022: APIs Drive Connectivity and Security Risk. Gartner Inc.
  5. McLean, T. (2015). "Critical vulnerabilities in JSON Web Token libraries." Auth0 Blog, March 31.
  6. IETF. (2025). RFC 9700: OAuth 2.0 Security Best Current Practice. Internet Engineering Task Force.
  7. Nightfall AI. (2023). 2023 Cloud Data Leak Report. Nightfall AI Inc.
  8. Shafranovich, Y. (2023). T-Mobile Data Breach Analysis. Internet Crime Complaint Center.
  9. OWASP. (2023). OWASP API Security Testing Guide. Open Web Application Security Project.
  10. Microsoft Research. (2022). RESTler: Stateful REST API Fuzzing. Microsoft Corporation.
  11. National Institute of Standards and Technology. (2024). SP 800-204C: Implementation of DevSecOps for a Microservices-based Application with API. NIST.

Further Reading

  • Anti-Phishing Working Group. (2023). APWG Phishing Activity Trends Report. APWG.