AI Guides
What Is API Security? A Practical Guide to API Gateway, REST, GraphQL, OAuth, JWT and Rate Limiting
A practical guide to API Security covering OWASP API Security Top 10, API Gateway security, REST and GraphQL controls, OAuth/OIDC, JWT, mTLS, rate limiting, schema validation, logging, monitoring and a 90-day rollout roadmap.
π‘Key Takeaways
- A practical guide to API Security covering OWASP API Security Top 10, API Gateway security, REST and GraphQL controls, OAuth/OIDC, JWT, mTLS, rate limiting, schema validation, logging, monitoring and a 90-day rollout roadmap.
GitHub Open Graph preview image for the OWASP/API-Security repository, used to illustrate OWASP API Security. Raster image, not SVG.1
GitHub Open Graph preview image for the Kong/kong repository, used to illustrate API Gateway. Raster image, not SVG.2
GitHub Open Graph preview image for the envoyproxy/envoy repository, used to illustrate proxy/service mesh/API traffic. Raster image, not SVG.3
GitHub Open Graph preview image for the apache/apisix repository, used to illustrate open-source API Gateway tooling. Raster image, not SVG.4
Quick summary
API Security is the practice of protecting APIs from unauthorized access, abuse, data leaks, business-logic attacks, injection, SSRF, brute force, credential stuffing, denial of service and misconfiguration. APIs may be REST, GraphQL, gRPC, WebSocket or internal service-to-service interfaces.
The OWASP API Security Top 10 2023 lists leading risks including Broken Object Level Authorization, Broken Authentication, Broken Object Property Level Authorization, Unrestricted Resource Consumption, Broken Function Level Authorization, Unrestricted Access to Sensitive Business Flows, SSRF, Security Misconfiguration, Improper Inventory Management and Unsafe Consumption of APIs.5 RFC 9700, OAuth 2.0 Security Best Current Practice, updates OAuth 2.0 security guidance based on practical experience and newer threats.6
Simple version: API Security is not βwe use JWT, so we are done.β You need correct authentication, authorization, input validation, rate limiting, schema validation, logging, token security, mTLS, API inventory, gateway policy and runtime monitoring.
Why APIs are major attack targets
APIs often provide direct access to data and business logic. Frontends can change and mobile apps can be reverse engineered, but the API is where real requests are processed.
A request may flow through:
Client
β
API Gateway / WAF
β
Auth service
β
Business API
β
Database / Queue / Third-party API
If API controls are weak, an attacker may:
- change
user_idto read another userβs data; - call an unprotected admin endpoint;
- brute force login or OTP flows;
- send large payloads to consume CPU or memory;
- spam ticket-buying, signup or checkout flows;
- exploit SSRF to call metadata services;
- abuse deep GraphQL queries;
- use leaked tokens;
- target old forgotten APIs;
- abuse trust in third-party API responses.
What API Security is not
| API Security is | API Security is not |
|---|---|
| Protecting identity, authorization, input, rate, data, logging and runtime | Only enabling HTTPS |
| Controls in both gateway and business services | Only installing a WAF |
| Object, property and function-level authorization | Only authenticating users |
| API inventory and lifecycle management | Leaving old APIs running forever |
| Policy, testing, monitoring and alerting | Only an annual pentest |
| Applies to REST, GraphQL, gRPC and internal APIs | Only public API protection |
HTTPS is necessary, but not enough. JWT is common, but not enough. API Gateway is useful, but it does not replace business-level authorization.
OWASP API Security Top 10 2023 in plain terms
| Code | Risk | Plain explanation |
|---|---|---|
| API1 | Broken Object Level Authorization | users access objects they do not own |
| API2 | Broken Authentication | login/token/session flaws allow identity takeover |
| API3 | Broken Object Property Level Authorization | users read or modify fields they should not access |
| API4 | Unrestricted Resource Consumption | API can be spammed or made expensive |
| API5 | Broken Function Level Authorization | users call admin or higher-privilege functions |
| API6 | Unrestricted Access to Sensitive Business Flows | business flows are abused by automation |
| API7 | Server Side Request Forgery | API fetches attacker-controlled URLs |
| API8 | Security Misconfiguration | CORS, headers, debug, TLS, error handling or config problems |
| API9 | Improper Inventory Management | old versions, debug endpoints or undocumented APIs |
| API10 | Unsafe Consumption of APIs | trusting third-party APIs too much |
Many API bugs are authorization and business logic bugs, not just code syntax bugs.
What is an API Gateway?
An API Gateway is a middle layer that receives client requests, applies shared policies and forwards them to backend services.
Client
β
API Gateway
βββ TLS termination
βββ authentication
βββ rate limiting
βββ request validation
βββ routing
βββ logging
βββ WAF / bot protection
βββ mTLS upstream
β
Backend APIs
An API Gateway is useful for:
- routing;
- TLS;
- JWT verification;
- OAuth/OIDC integration;
- rate limiting;
- IP allow/deny;
- request size limits;
- schema validation;
- CORS;
- logging, metrics and tracing;
- canary/blue-green routing;
- upstream mTLS;
- basic policy enforcement.
But the gateway should not be the only authorization layer. Object-level checks such as βcan this user read this order?β must be enforced in the service or near the business logic.
API Gateway does not replace service authorization
Dangerous example:
GET /api/orders/1001
Authorization: Bearer token-of-user-A
If user A changes the ID:
GET /api/orders/1002
The gateway usually does not know who owns order 1002. The backend must check:
order.user_id == current_user.id
If the backend does not check ownership, it is Broken Object Level Authorization.
Authentication vs Authorization
| Concept | Question | Example |
|---|---|---|
| Authentication | Who are you? | login, SSO, OIDC, API key, mTLS client cert |
| Authorization | What can you do? | RBAC, ABAC, ownership check, scope, policy |
| Accounting/Auditing | What did you do? | audit log, access log, security event |
Common mistake: βthe user is logged in, so access is allowed.β Login only establishes identity. Authorization decides permission.
OAuth, OIDC and JWT
OAuth 2.0
OAuth 2.0 is an authorization framework. It is often used to issue access tokens for clients to call APIs on behalf of users or services.
OpenID Connect
OpenID Connect is an identity layer on top of OAuth 2.0. OpenID Connect Core describes OIDC as a simple identity layer that allows clients to verify the identity of an end user based on authentication performed by an authorization server and obtain basic profile information.7
Use OIDC for login and SSO.
JWT
JWT is a compact, URL-safe token format for transferring claims between parties. RFC 7519 defines JWT as JSON claims that can be signed, integrity-protected or encrypted using JWS/JWE structures.8
JWT can be used as an access token or ID token, but not every access token must be a JWT.
JWT Security checklist
Common JWT failures:
- not verifying signatures;
- accepting
alg=none; - not checking
iss; - not checking
aud; - not checking
exp; - weak HS256 secrets;
- no key rotation;
- confusing ID tokens with access tokens;
- storing tokens in localStorage where XSS can steal them;
- overly long token lifetime;
- bad JWKS caching;
- logging tokens.
Checklist:
Verify signature
Validate issuer (iss)
Validate audience (aud)
Validate expiry (exp)
Validate not-before (nbf) if used
Validate token type/purpose
Use short-lived access tokens
Rotate signing keys
Do not log tokens
Do not put sensitive PII/secrets in JWT claims
Use RFC 8725 JWT BCP guidance
RFC 8725 provides best current practices for JSON Web Tokens and updates RFC 7519.9
OAuth 2.0 Security BCP: key points
RFC 9700 provides modern OAuth 2.0 security recommendations and updates older RFCs.6 For modern APIs, prioritize:
- Authorization Code Flow + PKCE for web, mobile and public clients;
- avoid Implicit Flow for new applications;
- strict redirect URI validation;
- short-lived access tokens;
- refresh token rotation where refresh tokens are used;
- limited scopes;
- audience-bound access tokens;
- sender-constrained tokens for higher-risk environments;
- mTLS or DPoP where token replay is a concern;
- avoid Resource Owner Password Credentials Grant for new apps;
- protect authorization server metadata;
- log and detect token abuse.
When to use API keys
API keys are simple and common for server-to-server or developer-platform access. They often identify an application/client, not an end user.
Use API keys for:
- public developer APIs;
- simple service integrations;
- usage tracking;
- rate limiting by client;
- lower-risk internal automation.
Do not rely only on API keys for:
- sensitive user-level access;
- personal data;
- admin APIs;
- financial transactions;
- flows requiring consent or user identity.
API key checklist:
- long random keys;
- store key hashes where possible;
- key prefixes for identification;
- scoped keys;
- expiration/rotation;
- rate limits by key;
- fast revocation;
- no keys in URL query strings;
- no key logging;
- show key only once when created.
When to use mTLS
mTLS means mutual TLS: the client and server authenticate each other with certificates. RFC 8705 defines OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens.10
Use mTLS for:
- internal service-to-service APIs;
- sensitive B2B APIs;
- finance or banking APIs;
- workload identity;
- reducing token replay risk;
- strong machine-to-machine authentication.
mTLS does not replace authorization. It authenticates the client/service, but the service must still decide what that client can access.
Rate limiting and quotas
Rate limiting helps prevent spam, brute force, scraping, bot abuse and resource exhaustion.
Types:
| Type | Example |
|---|---|
| Per IP | 100 requests/minute/IP |
| Per user | 1000 requests/hour/user |
| Per API key/client | 10,000 requests/day/app |
| Per endpoint | /login stricter than /status |
| Per tenant | quota by plan |
| Per token scope | lower scopes get lower limits |
| Concurrency limit | max 10 concurrent requests |
| Cost-based limit | GraphQL query cost |
RFC 9333 defines HTTP RateLimit fields that servers can use to communicate limits, remaining quota and reset time to clients.11
Practical examples:
/login: strict per account + per IP + bot detection
/search: per user + per IP + cache
/export: strict quota + async job
/graphql: query complexity + depth limit + timeout
/payment: idempotency key + anti-replay + business limit
Input validation and schema validation
APIs should validate data at multiple layers:
- gateway validates size, content type and basic schema;
- service validates business rules;
- database enforces constraints;
- output is filtered by permission.
OpenAPI schemas can define:
- endpoints;
- methods;
- path parameters;
- query parameters;
- request bodies;
- response shapes;
- auth schemes;
- status codes;
- versions.
The OpenAPI Initiative maintains the OpenAPI Specification for describing HTTP APIs.12
Schema validation should block:
- unexpected fields;
- wrong types;
- overly long strings;
- overly large arrays;
- deeply nested objects;
- wrong file upload content-type;
- oversized request bodies;
- invalid enums;
- invalid date/time formats.
REST API Security checklist
- Require HTTPS.
- Do not send tokens in query strings.
- Enforce object ownership.
- Enforce role/function authorization.
- Validate input with schemas.
- Limit request body size.
- Rate limit sensitive endpoints.
- Use idempotency keys for payment/order flows.
- Do not expose stack traces.
- Do not return sensitive fields by default.
- Log request_id/user_id_hash/trace_id.
- Use API versioning.
- Retire deprecated APIs.
- Test BOLA/BFLA cases.
- Configure CORS and security headers correctly.
GraphQL Security checklist
GraphQL has unique risks because clients choose query shape. GraphQL.org documents security controls such as validation, authorization, query depth, breadth, batch limiting and rate limiting.13
Checklist:
- depth limit;
- complexity/cost limit;
- timeout;
- disable introspection in production if not needed;
- persisted queries for official clients;
- field-level authorization;
- object-level authorization;
- rate limit by cost;
- mandatory pagination;
- batch query limits;
- avoid exposing detailed resolver errors;
- log operation name/hash;
- review schema changes for sensitive fields.
Example risk:
query {
users {
id
email
orders {
id
paymentInfo {
cardLast4
}
}
}
}
Without field-level authorization, users may retrieve sensitive fields they should not see.
CORS misconfiguration
CORS is not authentication. It only tells browsers which origins can read responses.
Bad pattern:
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Recommendations:
- allowlist specific origins;
- do not use wildcard for credentialed requests;
- separate dev/staging/prod origins;
- do not blindly reflect Origin;
- control allowed methods and headers;
- use preflight cache carefully;
- never treat CORS as the only security layer.
SSRF in APIs
SSRF occurs when an API accepts a URL from a user and the server fetches it without proper validation. OWASP API7:2023 says SSRF can happen when an API fetches a remote resource without validating a user-supplied URI, allowing an attacker to force the application to send a request to an unexpected destination.5
Dangerous example:
POST /fetch-url
{
"url": "http://169.254.169.254/latest/meta-data/"
}
Mitigations:
- allowlist domains;
- block private IP ranges;
- resolve DNS and re-check IP;
- disable or control redirects;
- short timeouts;
- block non-HTTP schemes;
- do not forward credentials;
- egress firewall;
- cloud metadata protection;
- dedicated outbound proxy.
API inventory and lifecycle
OWASP API9:2023 highlights improper inventory management because APIs expose many endpoints and require updated documentation and inventory.5
Track:
- public/internal/partner APIs;
- owner;
- deployed versions;
- deprecated endpoints;
- auth scheme;
- data classification;
- rate limits;
- logs and monitoring;
- downstream dependencies;
- dev/staging/prod environments.
You cannot protect old APIs you do not know exist.
Logging and monitoring for API Security
Log:
- request_id/trace_id;
- hashed user_id;
- client_id/API key id;
- endpoint/method/status;
- latency;
- safe auth failure reason;
- rate limit events;
- policy denies;
- suspicious input;
- token issuer/audience mismatch;
- unusual geography/device pattern;
- admin actions;
- exports/downloads;
- third-party API failures.
Do not log:
- access tokens;
- refresh tokens;
- API keys;
- passwords;
- OTP codes;
- full credit card data;
- unnecessary private data;
- raw sensitive payloads.
Useful alerts:
Login failure spike
Token validation failure spike
403 spike on sensitive endpoint
Rate limit exceeded spike
SSRF pattern
High 5xx after deployment
GraphQL query cost spike
Mass export/download
Deprecated API traffic
Abnormal third-party API response
API Security testing
Use automated and manual testing.
Automated
- OpenAPI schema linting;
- SAST;
- dependency scanning;
- DAST;
- fuzzing;
- contract testing;
- secrets scanning;
- container scanning;
- IaC scanning;
- endpoint discovery.
Manual
- BOLA: change object IDs;
- BFLA: call admin functions;
- property-level auth: add forbidden fields;
- mass assignment;
- rate limit bypass;
- token tampering;
- CORS test;
- SSRF test;
- GraphQL depth/cost abuse;
- business logic abuse.
OWASP ZAP is a widely used proxy/security testing tool for web and API testing.14
30/60/90-day rollout roadmap
Days 1β30: foundation
- Build API inventory.
- Require HTTPS.
- Standardize auth: OAuth/OIDC/JWT/API key.
- Check JWT validation: iss, aud, exp, signature.
- Add rate limits for login, OTP, search and export.
- Log request_id/trace_id/client_id.
- Disable debug endpoints and stack traces.
- Configure CORS allowlist.
- Block oversized request bodies.
- Review sensitive endpoints against OWASP API Top 10.
Days 31β60: gateway and policy
- Put important APIs behind an API Gateway.
- Add OpenAPI schema validation.
- Separate public, internal and admin APIs.
- Add RBAC/ABAC policy.
- Add BOLA/BFLA tests.
- Add GraphQL depth/cost limits if GraphQL is used.
- Add mTLS for service-to-service or sensitive partner APIs.
- Build API dashboard: rate, error, latency, auth failures.
- Alert on abuse patterns.
Days 61β90: advanced controls
- Token rotation and JWKS cache policy.
- Sender-constrained tokens with mTLS/DPoP where needed.
- Bot detection for sensitive flows.
- API discovery and shadow API detection.
- Scheduled DAST/fuzzing.
- Threat modeling for important APIs.
- Third-party API consumption review.
- Deprecated API retirement plan.
- Fine-grained authorization service for larger systems.
- Incident playbooks: leaked token/API key, BOLA, mass scraping.
Quick checklist
Auth
- OIDC for user login.
- OAuth access tokens for APIs.
- API keys for developer/server integrations where suitable.
- mTLS for sensitive machine-to-machine traffic.
- Do not invent token formats unnecessarily.
- Avoid long-lived tokens for public clients.
JWT
- Verify signature.
- Validate
iss,aud,exp,nbf. - Algorithm allowlist.
- Key rotation.
- No token logging.
- No sensitive PII in claims.
- Short-lived access tokens.
- Protect refresh tokens separately.
Authorization
- Object-level authorization.
- Property-level authorization.
- Function-level authorization.
- Clear RBAC/ABAC.
- Deny by default.
- Policy tests in CI.
- Admin action auditing.
Gateway
- TLS.
- Routing.
- Rate limiting.
- Request size limits.
- Schema validation.
- JWT verification.
- CORS policy.
- Logging/tracing.
- WAF/bot protection where needed.
Data
- Do not return sensitive fields by default.
- Output filtering by permission.
- Mandatory pagination.
- Separate export permission.
- Data classification.
- Masking/tokenization where needed.
Runtime
- API dashboard.
- Alerts for auth/rate/security events.
- Deprecated API traffic detection.
- Third-party API monitoring.
- Incident runbooks.
- Log retention and privacy policy.
Reference tooling
| Need | Tool/standard |
|---|---|
| API risk framework | OWASP API Security Top 10 |
| API documentation/schema | OpenAPI |
| API Gateway | Kong, Envoy, NGINX, Apache APISIX, Traefik |
| OAuth/OIDC | Keycloak, Auth0, Okta, Azure AD/Entra ID, Zitadel |
| JWT standard | RFC 7519, RFC 8725 |
| OAuth security | RFC 9700 |
| OAuth mTLS | RFC 8705 |
| API testing | OWASP ZAP, Postman/Newman, Schemathesis |
| API discovery | APIClarity, gateway logs, service catalog |
| Observability | OpenTelemetry, Prometheus, Grafana, Loki, Tempo |
| Policy | OPA, Cedar, OpenFGA, custom authorization service |
Common mistakes
- Believing API Gateway replaces backend authorization.
- Using JWT without validating
audoriss. - Confusing ID tokens with access tokens.
- Long-lived tokens.
- API keys in URL query strings.
- CORS wildcard with credentials.
- No rate limiting for login, OTP or export.
- GraphQL without depth/cost limits.
- No API inventory.
- Old APIs running without owners.
- Access tokens logged into log platforms.
- Over-trusting third-party API data.
- Only testing happy paths.
- No owner for API lifecycle.
FAQ
What is API Security?
API Security is the practice of protecting APIs from unauthorized access, abuse, data leaks, authorization bugs, injection, SSRF, resource exhaustion and misconfiguration.
Is an API Gateway enough?
No. An API Gateway helps with shared controls such as TLS, JWT verification, rate limiting, logging and routing. Object-level authorization, property-level authorization and business rules must still be enforced in backend services or authorization layers.
How are OAuth and OIDC different?
OAuth 2.0 is an authorization framework. OpenID Connect is an identity layer on top of OAuth 2.0, used for authentication/login and user identity information.7
Is JWT secure?
JWT is a token format. Security depends on issuance, signing, validation, storage, rotation and lifetime. RFC 7519 defines JWT, and RFC 8725 provides best current practices.89
Where should rate limiting happen?
Put basic rate limiting at the gateway/WAF to block early. Some business limits must be enforced in services, such as ticket purchases, OTP sends, exports and tenant quotas.
Is GraphQL more dangerous than REST?
Not inherently, but GraphQL has specific risks such as query depth, complexity, batching, introspection exposure and field-level authorization. It needs GraphQL-specific controls.13
Conclusion
API Security is a core discipline for modern IT systems. APIs expose data and business logic directly, so authorization flaws, token validation gaps, missing rate limits or poor inventory can have high impact. Good API Security combines multiple layers: gateway policy, standard OAuth/OIDC/JWT usage, backend authorization, schema validation, rate limiting, mTLS, logging, monitoring and continuous security testing.
Start with API inventory, HTTPS, token validation, rate limits for sensitive endpoints, correct CORS, safe logging and OWASP API Security Top 10 review. Then mature into schema validation, GraphQL protection, mTLS, API discovery, DAST/fuzzing, fine-grained authorization and incident response.
References
Footnotes
-
GitHub Open Graph preview image for
OWASP/API-Security. https://opengraph.githubassets.com/api-security-guide/OWASP/API-Security β© -
GitHub Open Graph preview image for
Kong/kong. https://opengraph.githubassets.com/api-security-kong-guide/Kong/kong β© -
GitHub Open Graph preview image for
envoyproxy/envoy. https://opengraph.githubassets.com/api-security-envoy-guide/envoyproxy/envoy β© -
GitHub Open Graph preview image for
apache/apisix. https://opengraph.githubassets.com/api-security-apisix-guide/apache/apisix β© -
OWASP API Security Top 10 2023. https://owasp.org/API-Security/editions/2023/en/0x11-t10/ β© β©2 β©3
-
RFC 9700, Best Current Practice for OAuth 2.0 Security. https://datatracker.ietf.org/doc/html/rfc9700 β© β©2
-
OpenID Connect Core 1.0. https://openid.net/specs/openid-connect-core-1_0.html β© β©2
-
RFC 7519, JSON Web Token. https://datatracker.ietf.org/doc/html/rfc7519 β© β©2
-
RFC 8725, JSON Web Token Best Current Practices. https://datatracker.ietf.org/doc/html/rfc8725 β© β©2
-
RFC 8705, OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens. https://datatracker.ietf.org/doc/html/rfc8705 β©
-
RFC 9333, RateLimit Fields for HTTP. https://datatracker.ietf.org/doc/html/rfc9333 β©
-
OpenAPI Initiative. https://www.openapis.org/ β©
-
GraphQL.org Security. https://graphql.org/learn/security/ β© β©2
-
OWASP ZAP. https://www.zaproxy.org/ β©
Written by PixelRouter Editorial Team
We publish deep, authoritative guides on AI infrastructure, API gateway security, cloud financial management, and system optimizations for developers.
FAQ
What is API Security?
API Security is the practice of protecting APIs from unauthorized access, abuse, data leaks, authorization bugs, injection, SSRF, resource exhaustion and misconfiguration.
Is an API Gateway enough for API security?
No. An API Gateway can help with shared controls such as TLS, JWT verification, rate limiting, logging and routing, but object-level authorization, property-level authorization and business rules still need to be enforced in backend services or authorization layers.
How are OAuth and OIDC different?
OAuth 2.0 is an authorization framework. OpenID Connect is an identity layer on top of OAuth 2.0 used for authentication, login and user identity information.
Is JWT secure?
JWT is a token format. Its security depends on how tokens are issued, signed, validated, stored, rotated and expired.
Where should rate limiting happen?
Basic rate limiting should happen at the gateway or WAF to block abusive traffic early. Business-specific limits, such as OTP sends, exports, ticket purchases or tenant quotas, should be enforced in services.
Is GraphQL more dangerous than REST?
Not inherently, but GraphQL has specific risks such as query depth, complexity, batching, introspection exposure and field-level authorization, so it needs GraphQL-specific security controls.
πRelated posts
AI Guides
YouTube Copyright Policy 2026: Content ID, Strikes, Fair Use, and How to Respond
A practical guide to YouTube copyright policy, explaining Content ID claims, copyright strikes, fair use, Creative Commons, public domain, disputes, counter notifications, and creator checklists.
AI Guides
YouTube Policies Creators Should Know Beyond Deceptive Content
A creator-focused guide to YouTube policy areas beyond deceptive content, including harmful content, child safety, harassment, violent or graphic content, regulated goods, copyright, and monetization rules.
AI Guides
YouTube Deceptive Content Policy Part 3: Pre-Publish Compliance Workflow
A practical workflow for creators to review YouTube titles, thumbnails, descriptions, external links, AI-generated content, impersonation risks, warnings, and strikes before publishing.