Protego field desk
Cybersecurity20 min read

OWASP API Security Top 10 2023: Complete Developer Guide with Real Examples

The OWASP API Security Top 10 2023, risk by risk: how each attack works, the vulnerable code, the fix, and a checklist to run before you ship an API endpoint.

I
Microsoft Cloud Solution Architect
Updated

Quick answer

The OWASP API Security Top 10 (2023) lists the ten most critical API risks, led by Broken Object Level Authorization (API1): an endpoint returns another user's record when the ID is changed. Fix it with an ownership check on every object access, explicit field allow-lists, rate and size limits, and an inventory of every API version you run.

OWASP API Security Top 10 2023: Complete Developer Guide with Real Examples infographic showing key Cybersecurity concepts and controls
OWASP API Security Top 10 2023: Complete Developer Guide with Real Examples infographic showing key Cybersecurity concepts and controls
OWASPAPI SecurityREST APIBroken Object Level AuthorizationJWTBOLAAPI vulnerabilitiesWeb Security

Why APIs Are Now the #1 Attack Surface

Many breaches need no kernel exploit and no decade-old CVE. They use an API endpoint that does exactly what it was told, just for someone who should not have been asking. OWASP ranks that failure, Broken Object Level Authorization, as the number one API risk.

APIs connect mobile apps, partner integrations, microservices and internal tools, and many organizations have no complete list of the APIs they expose. OWASP names this directly in API9 (Improper Inventory Management): old versions and debug endpoints stay online, unpatched and outside the security controls of the current API.

OWASP published the API Security Top 10 2023 as an update to the 2019 edition. It merged Excessive Data Exposure and Mass Assignment into API3 (Broken Object Property Level Authorization), added Unrestricted Access to Sensitive Business Flows, Server Side Request Forgery and Unsafe Consumption of APIs, and dropped Injection and Insufficient Logging and Monitoring as separate entries.

This guide walks through all ten risks with the attack pattern, vulnerable code, and the fix.

API1:2023 - Broken Object Level Authorization (BOLA)

What it is: the top-ranked API risk, which OWASP rates as easy to exploit and widespread. An attacker reads or changes another user's data by changing an object identifier in the request. The ID can be a sequential number, a UUID or a string, in the path, query string, headers or body.

Attack pattern:

GET /api/v1/invoices/1234    ← Attacker's invoice
GET /api/v1/invoices/1235    ← Different user's invoice (just increment the ID)
GET /api/v1/invoices/1236    ← Another user's invoice

Vulnerable code:

// VULNERABLE: Only checks auth, not ownership
app.get('/api/v1/invoices/:id', authenticate, async (req, res) => {
  const invoice = await Invoice.findById(req.params.id)
  res.json(invoice)  // Returns any invoice if you know the ID
})

Fixed code:

// SECURE: Checks ownership before returning data
app.get('/api/v1/invoices/:id', authenticate, async (req, res) => {
  const invoice = await Invoice.findOne({
    _id: req.params.id,
    userId: req.user.id  // Must belong to the requesting user
  })
  if (!invoice) return res.status(404).json({ error: 'Not found' })
  res.json(invoice)
})

Use non-guessable UUIDs instead of sequential IDs to reduce enumeration risk, but never treat UUIDs as a security control. Authorization logic is the fix.

API2:2023 - Broken Authentication

What it is: Weak authentication mechanisms - missing rate limiting on login endpoints, weak JWT implementation, credentials in query strings, long-lived tokens without rotation.

Common vulnerabilities:

PatternProblem
No rate limit on /auth/loginCredential stuffing and brute force
JWT signed with HS256 + weak secretOffline brute-force of the signing key
JWT with alg: none acceptedSignature verification bypassed
Access token valid for 30 daysLong window for stolen token abuse
Credentials in URL query paramsLogged in proxy/server logs, browser history

Dangerous JWT vulnerability:

// VULNERABLE: Accepting 'none' algorithm
const decoded = jwt.verify(token, secret, { algorithms: ['HS256', 'none'] })

// SECURE: Explicitly restrict to expected algorithm
const decoded = jwt.verify(token, secret, { algorithms: ['HS256'] })

Best practices: short-lived access tokens (for example 15 minutes) with refresh token rotation, PKCE for OAuth flows, rate limiting with exponential backoff on auth endpoints, and MFA for sensitive operations. The JWT guide covers algorithm pinning and claim validation in depth, and the JWT decoder shows what a real token carries without sending it anywhere.

API3:2023 - Broken Object Property Level Authorization

What it is: APIs expose more object properties than the caller should be able to see or modify: either over-fetching (exposing sensitive fields) or over-posting (accepting fields that shouldn't be writable).

Over-exposure attack:

// API returns full user object including internal fields
{
  "id": "123",
  "email": "user@example.com",
  "name": "Alice",
  "role": "admin",           ← Should not be exposed to end users
  "internalUserId": "USR_89",
  "creditCardLast4": "4242",  ← Sensitive field exposed unnecessarily
  "passwordResetToken": "abc" ← Critical: token in response!
}

Mass assignment attack (over-posting):

PATCH /api/v1/profile
{
  "name": "Alice",
  "email": "alice@example.com",
  "role": "admin",        ← Attacker adds this, API accepts it
  "isVerified": true      ← And this
}

Fix: Use explicit allow-lists for response serialization and request deserialization. Never bind request body directly to database models.

// SECURE: Explicit allow-list for what can be updated
const ALLOWED_UPDATE_FIELDS = ['name', 'email', 'bio', 'avatar']

app.patch('/api/v1/profile', authenticate, async (req, res) => {
  const updates = pick(req.body, ALLOWED_UPDATE_FIELDS)  // lodash.pick or equivalent
  await User.findByIdAndUpdate(req.user.id, updates)
  res.json({ success: true })
})

API4:2023 - Unrestricted Resource Consumption

What it is: No limits on request rate, payload size, query complexity, or execution time, enabling DoS, resource exhaustion, and financial attacks (scraping paid APIs).

Attack vectors:

  • High-frequency requests draining rate-limited paid services you're proxying
  • Large file upload payloads consuming memory/disk
  • Deep GraphQL queries or nested joins causing CPU spikes
  • Webhook abuse - attacker-controlled endpoints causing thousands of outbound calls

Mitigations:

// Rate limiting example (express-rate-limit)
const rateLimit = require('express-rate-limit')

const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,  // 15 minutes
  max: 100,                    // 100 requests per window per IP
  message: { error: 'Too many requests' },
  standardHeaders: true,
  legacyHeaders: false,
})

app.use('/api/', apiLimiter)

// Payload size limits
app.use(express.json({ limit: '10kb' }))  // Reject large JSON bodies
app.use(express.urlencoded({ limit: '10kb', extended: true }))

Also: set explicit timeouts on all external calls, implement pagination with max page size, and set GraphQL query depth/complexity limits.

API5:2023 - Broken Function Level Authorization

What it is: Admin or privileged functions are accessible to non-admin users because the API doesn't check the caller's role, only their authentication.

Pattern:

DELETE /api/v1/admin/users/456   ← Works even as a regular user if no role check
POST /api/v1/internal/export     ← "Internal" in the path doesn't mean restricted

Vulnerable pattern:

// VULNERABLE: Only checks authentication
router.delete('/admin/users/:id', authenticate, deleteUser)

// SECURE: Checks authentication + role
router.delete('/admin/users/:id', authenticate, requireRole('admin'), deleteUser)

Combine BFLA protection with:

  • Separate admin API surface (different subdomain or port, IP-restricted)
  • Role claims in JWT that are server-verified on every request
  • Audit logging of all privileged function calls

API6:2023 - Unrestricted Access to Sensitive Business Flows

What it is: Legitimate endpoints exploited at scale to abuse business logic: account creation for spam, inventory reservation attacks, coupon/promo code abuse, ticket scalping bots.

Unlike other API risks, these endpoints work exactly as designed, just not at the scale or by the actor intended.

Examples:

  • Bots creating thousands of accounts with fake email addresses
  • Competitors scraping your entire product catalog and pricing
  • Reserving all available inventory in an e-commerce system then abandoning
  • Referral fraud - creating fake accounts to claim referral bonuses

Mitigations: CAPTCHA on high-value flows, device fingerprinting, behavioral anomaly detection (flag account creation bursts), phone/email verification before granting full access, business-logic rate limits (max 3 accounts per device/IP/phone number).

API7:2023 - Server-Side Request Forgery (SSRF)

What it is: User-controlled input causes the server to make HTTP requests to internal services, cloud metadata endpoints, or arbitrary external URLs.

Attack in cloud environments:

POST /api/v1/fetch-preview
{
  "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/prod-role"
}

If the instance still allows IMDSv1, the server fetches the AWS metadata endpoint and hands the attacker the instance role's temporary credentials, with whatever permissions that role has. Requiring IMDSv2, which needs a session token obtained with a PUT request, blocks this simple GET-based form.

Fix:

const { URL } = require('url')
const dns = require('dns').promises

async function isSafeUrl(inputUrl) {
  const parsed = new URL(inputUrl)
  // Block non-HTTP protocols
  if (!['http:', 'https:'].includes(parsed.protocol)) return false
  // Block private/loopback ranges
  const addresses = await dns.resolve4(parsed.hostname)
  return addresses.every(ip => !isPrivateIP(ip))  // implement isPrivateIP check
}

The check above is a starting point, not a complete defense. An attacker can make a hostname resolve to a public address during the check and a private one at fetch time (DNS rebinding), or use an IPv6 address or a redirect. Connect to the address you validated, re-check every redirect hop or disable redirects, prefer an allowlist of permitted domains, and run the fetcher in a network segment with no route to internal services.

API8:2023 - Security Misconfiguration

What it is: Default configurations, excessive permissions, missing security headers, verbose error messages, unnecessary HTTP methods, and permissive CORS.

Most common API misconfigurations:

MisconfigurationImpact
CORS reflects any Origin and allows credentialsAny website can make credentialed requests and read the responses (browsers refuse credentials with a literal *, so this is the real risk)
Verbose errors in productionStack traces expose framework versions, file paths, SQL queries
HTTP methods not restrictedDELETE, PUT accepted on read-only resources
No security headersMissing X-Content-Type-Options, Strict-Transport-Security
Debug endpoints in production/debug, /actuator, /metrics expose internal state
Swagger UI publicly accessibleExposes full API documentation including internal endpoints

Secure defaults:

// CORS: explicit allowlist
app.use(cors({
  origin: ['https://yourapp.com', 'https://admin.yourapp.com'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
}))

// Generic error responses in production
app.use((err, req, res, next) => {
  if (process.env.NODE_ENV === 'production') {
    return res.status(500).json({ error: 'Internal server error' })  // No details
  }
  res.status(500).json({ error: err.message, stack: err.stack })
})

API9:2023 - Improper Inventory Management

What it is: Shadow APIs, deprecated API versions still active, undocumented endpoints, and APIs exposed through third-party services that bypass your security controls.

Why this matters: You can't secure what you don't know exists. Shadow APIs often arise from:

  • API versions never properly deprecated (v1 still active when v3 is current)
  • Developer/test APIs promoted to production without security review
  • Third-party integrations that create undocumented API exposure
  • Microservices that expose internal APIs without going through the API gateway

Inventory controls:

  • API gateway as the single entry point - no direct service-to-internet exposure
  • API discovery from gateway logs and traffic analysis (commercial API security platforms do this), plus DNS enumeration and certificate transparency searches for forgotten hosts such as beta or old-version subdomains
  • OpenAPI/Swagger specs enforced as part of CI/CD (PR blocks if spec not updated)
  • Regular nmap scans of your own perimeter to find unexpected open ports/endpoints
  • Version sunset policy: v1 deprecated → 90 days notice → disabled

API10:2023 - Unsafe Consumption of APIs

What it is: Your application consumes third-party APIs and trusts them unconditionally (not validating responses, following all redirects, or executing received content), making your application an attack vector when the upstream API is compromised.

Attack scenario:

  1. Attacker compromises a weather API your application uses
  2. The compromised API returns a malicious payload in a field your code injects into HTML
  3. Your users get XSS despite your own code being clean

Mitigations:

// Validate and sanitize ALL data from external APIs
const externalData = await thirdPartyApi.getData()

// Validate schema
const validatedData = externalApiSchema.parse(externalData)  // Zod, Joi, etc.

// Sanitize any string fields before rendering
const safeName = sanitizeHtml(validatedData.name, { allowedTags: [] })

// Never execute content from external APIs
// eval(externalData.script)  ← Never do this

Also: use TLS for every integration, set timeouts and resource limits on outbound calls, do not follow redirects blindly (allowlist redirect targets), and monitor for unexpected changes in response structure, which can indicate a compromised upstream API.

API Security Testing Checklist

Before shipping any API endpoint, verify:

Authorization

  • [ ] Every endpoint checks object ownership (BOLA), not just authentication
  • [ ] Admin/privileged functions check caller's role
  • [ ] Object IDs are UUIDs, not sequential integers (defense-in-depth)

Authentication

  • [ ] JWT algorithm explicitly restricted (no alg: none)
  • [ ] Token expiry ≤ 15 minutes for access tokens
  • [ ] Rate limiting on all auth endpoints

Input/Output

  • [ ] Response serialization uses explicit field allow-list
  • [ ] Request body allow-list (no mass assignment)
  • [ ] Payload size limits configured

Infrastructure

  • [ ] CORS configured with explicit origin allowlist
  • [ ] No verbose error messages in production
  • [ ] Swagger/docs not publicly accessible (or restricted to internal network)
  • [ ] HTTP methods restricted to what's used

Monitoring

  • [ ] Authentication failures logged and alerted
  • [ ] Unusual access patterns (BOLA enumeration) detectable in logs
  • [ ] API version inventory maintained and documented

The OWASP API Security Top 10 is a framework, not a checklist. The goal isn't to check boxes; it's to build the mental model of how APIs fail. Once you understand that authorization logic must be applied per-object (not just per-endpoint), that JWT implementation bugs are a class of their own, and that your trust in third-party APIs is a liability, the secure patterns become intuitive rather than memorized.

For organizations building APIs at scale, pair this with the DevSecOps CI/CD guide to automate API security testing (DAST, schema validation, auth testing) into your pipeline rather than relying on pre-release manual review.

Frequently Asked Questions

What is the OWASP API Security Top 10?

The OWASP API Security Top 10 (2023 edition) is OWASP's ranked list of the most critical API security risks: API1 Broken Object Level Authorization (BOLA), API2 Broken Authentication, API3 Broken Object Property Level Authorization, API4 Unrestricted Resource Consumption, API5 Broken Function Level Authorization, API6 Unrestricted Access to Sensitive Business Flows, API7 Server Side Request Forgery, API8 Security Misconfiguration, API9 Improper Inventory Management and API10 Unsafe Consumption of APIs.

What is BOLA and why is it the top API risk?

BOLA (Broken Object Level Authorization) means an API returns or changes an object without checking that the caller may access that specific object, for example changing /api/orders/1234 to /api/orders/1235 to read another user's order. OWASP ranks it first because it is easy to exploit and widespread: authentication succeeds, and only a per-object authorization check stops it.

What is the difference between BOLA and BFLA?

BOLA (API1) is horizontal: a user reaches another user's objects at the same privilege level. BFLA (Broken Function Level Authorization, API5) is vertical: a regular user calls a function meant for admins, such as DELETE /api/admin/users. Both need server-side authorization checks in code, not just a valid token.

How do I protect APIs against broken authentication?

Pin the accepted JWT algorithms and reject alg none, validate the issuer, audience and expiry on every request, and keep access tokens short-lived with refresh token rotation. Rate-limit login and token endpoints against credential stuffing, use PKCE for public OAuth clients, and never put credentials or tokens in URLs, where proxies and logs record them.

How do I test my APIs for OWASP Top 10 issues?

Combine SAST (for example Semgrep) for insecure code patterns, DAST driven by your OpenAPI spec (OWASP ZAP or Burp Suite) and a REST API fuzzer such as Microsoft's RESTler or Schemathesis. Add manual or scripted tests with two test users that try to read each other's objects, because automated scanners often miss BOLA.

Sources

RD / 01

Reader desk

Discuss this guide

Rate the guide or ask a practical follow-up. Clear questions publish immediately; uncertain submissions wait for review.

Get the free Cloud Security Checklist

A 20-point hardening checklist for AWS, Azure, and GCP workloads. No spam, unsubscribe anytime.

I

Microsoft Cloud Solution Architect

Cloud Solution Architect with deep expertise in Microsoft Azure and a strong background in systems and IT infrastructure. Passionate about cloud technologies, security best practices, and helping organizations modernize their infrastructure.

Share this article

Licensed under CC BY 4.0: you may share and adapt this article with attribution to Protego.