API security begins with understanding that APIs connect web applications, mobile apps, internal services, and third-party systems. Because APIs often return data directly, authentication or authorization errors can have more serious consequences than typical UI bugs. Unprotected endpoints can also be exploited to drain resources or retrieve data the caller is not entitled to access.
1. Distinguish Authentication from Authorization
Authentication answers “who is the caller?” while authorization determines “what are they allowed to do?” APIs must verify both for every sensitive operation. Do not assume a user is entitled to read an object simply because they are logged in or know the object’s ID. Check ownership and permissions server-side for every request.
2. Manage Tokens and API Keys Securely
Never embed API secrets in frontend code, public repositories, or downloadable configuration files. Store secrets in a secret manager or protected server environment, restrict their access rights, and rotate credentials when a leak is suspected. Tokens should have expiration times, scope limitations, and revocation mechanisms as needed. Never place tokens in URLs, as they may be logged in server logs or browser history.
3. Validate Input and Enforce Schemas
Check type, length, format, and allowed values for every parameter. Reject unknown properties if the API design permits, limit payload size, and use parameterized database queries. Input validation must be paired with context-appropriate output encoding—these are two distinct steps. The Content Security Policy guide explains additional browser-side defenses, but CSP does not replace server-side validation.
4. Implement Rate Limiting and Resource Controls
Set request limits based on user, token, IP address, and endpoint sensitivity. Expensive operations such as complex searches, data exports, OTP delivery, or report generation may require different thresholds. Provide consistent responses when limits are exceeded and log abuse patterns. Rate limiting helps mitigate exploitation impact but does not replace DDoS protection at the network layer.
5. Use Secure Transport
Use HTTPS for all endpoints carrying credentials or user data. Validate certificates on the client side and avoid disabling TLS checks to work around errors. Restrict administrative endpoints, apply network controls where appropriate, and never rely on URL secrecy as an access control mechanism.
6. Configure CORS Properly
CORS is a browser policy that determines whether a page from one origin may read responses from another origin. CORS is not an authentication system. Avoid reflexively allowing all origins, especially if the API uses cookies or credentials. Specify only the origins, methods, and headers actually required. For sensitive actions, still perform authentication, authorization, and CSRF protection according to the application’s authentication method.
7. Log, Monitor, and Test
Log authentication failures, authorization denials, traffic spikes, and server errors—without recording passwords, complete tokens, or unnecessary sensitive data. Create alerts for unusual patterns, update dependencies regularly, and test APIs with every meaningful change. Also verify that error messages do not leak stack traces or internal details.
Start with a Checklist
- Every sensitive endpoint verifies authentication and permissions on the server.
- Every object is checked for access rights, not just its ID.
- Secrets are not stored in the frontend or public repositories.
- Requests have schema validation and size limits.
- Rate limits, logging, and alerts are tested in realistic scenarios.
A layered defense model aligns with Zero Trust Security principles. If public APIs sit behind a CDN or protection service, also understand website protection from DDoS attacks.
Common Mistakes Teams Make
Many API security problems do not come from sophisticated attacks. They come from small design mistakes that seem harmless at first. One of the most common is relying on predictable object IDs without checking ownership. If an endpoint returns data based only on the ID supplied by the caller, anyone who changes that ID can read someone else’s data. This problem is known as broken object level authorization, and the fix is straightforward: check on the server, for every request, whether the caller is entitled to access the requested object, with no exceptions.
Another frequent mistake is error messages that reveal too much. Messages such as “no user with this email exists” or “wrong password for this account” help an attacker work out which accounts are valid. Error messages shown to users should stay generic, while technical detail belongs only in internal logs that are not exposed to clients. The same applies to stack traces: never show internal file names or framework details to the caller.
Tokens that never expire are another source of risk. An access token that lasts forever means a single leak grants access without any time limit. Set a reasonable lifetime, provide a safe refresh mechanism, and make sure tokens can be revoked immediately when a leak is suspected. The same rule applies to API keys: keys created for testing should never be left active in production.
- Do not rely on URL secrecy as the only protection for an endpoint.
- Do not allow all origins in CORS when the API uses cookies or credentials.
- Do not store secrets in repositories, downloadable configuration files, or application logs.
- Do not return more data than the client needs, because extra data increases the impact of any leak.
- Do not assume internal endpoints are safe only because they are not published—internal networks can be breached too.
Public APIs Need Different Rules
Public and internal APIs need different approaches, even though the core principles are the same. A public API is used by parties you do not control, so its limits should be stricter: lower rate limits, harder schema validation, and clear documentation about what is and is not allowed. Plan API versioning from the start, so behaviour changes do not break existing integrations and security policy can be tightened in a new version without forcing every client to migrate at once.
Internal APIs are often assumed safe because they are only reachable from inside the network. That assumption is dangerous. If one internal service is compromised, an attacker can move to other unprotected services. Apply authentication between services, restrict network access between segments, and check permissions on internal calls just as strictly as on external ones. Trust should come from verified identity and permissions, not from network location.
For APIs used by mobile apps, remember that an app installed on a user’s device cannot store a secret safely. Never embed a permanent secret inside the app. Issue short-lived tokens after the user signs in, and design endpoints so the damage from a stolen token stays limited.
Test Your API Like an Attacker Would
API security testing should be a routine part of development, not a once-a-year activity. Start by listing every endpoint, including ones that have not been used in a long time. Forgotten endpoints often miss security updates and become an easy way in. Remove endpoints that are no longer needed.
Test authorization by trying to access another user’s data with an ordinary user’s token. Test validation by sending unusual input: very long strings, wrong data types, unexpected extra properties, and values outside the allowed range. Test rate limiting by sending bursts of requests and confirming that limits are actually enforced, not only written in documentation.
Also test your logs and alerts by simulating suspicious behaviour, such as many failed logins from one address in a short time. If no alert appears, your monitoring is not ready for a real incident. Record the results and fix findings in order of risk, starting with the most damaging ones.
What to Do When a Secret Leaks
Credential leaks can happen to any team, and the speed of the response decides how bad the impact becomes. The first step is to revoke the leaked credential and replace it, then check the logs to see whether it was already used by someone unauthorised. Look for unusual activity: access to rarely used endpoints, a sudden large volume of downloaded data, or logins from unfamiliar locations.
Next, find the source of the leak and close it. Check whether the secret was committed to a repository, shared in a message, or printed in a log. If user data was affected, tell the affected users clearly what happened and what they should do, such as changing passwords or reviewing account activity.
Finally, turn the incident into an improvement: tighten where secrets are stored, add automated scanning to catch secrets that accidentally enter code, and train the team so everyone knows what to do when the next incident happens. A secure API is not one that never has problems; it is one that recovers quickly and learns from every incident.
Conclusion
API security is not a single middleware installed once and forgotten. Apply access verification at every endpoint, limit resources, protect secrets, and monitor usage over time.
References
Use the OWASP API Security Project for risk mapping and testing checklists.

Leave a comment