API Security Best Practices for AI-Built Applications

Quick answer: Review reachable API endpoints for authentication, object-level authorization, input validation, query construction, and resource limits. Configure CORS for intended browser access, but enforce permissions on the server. Test sensitive operations independently of whether the frontend exposes a button for them.

By Daniel A · Kraftwire Software

· 11 min read

For AI-built APIs, enforce authentication and authorization where required, validate inputs, bind database values as query parameters, and limit resource use. The frontend cannot enforce server permissions. Configure CORS for intended browser access and test sensitive operations through the API directly.

The Reality of API Security in AI-Built Apps

An API defines how software requests data or actions from other software. For a reachable web API, a caller can construct requests without using the application’s interface. The server must decide which operations are allowed.

Review exposed API endpoints for unauthorized data access and resource-exhaustion risks.

Review the API’s Callers and Permissions

Frontends, mobile clients, integrations, and webhooks can interact through APIs. Define the expected callers, data, and permitted operations for each endpoint, including deliberately public features.

For reachable endpoints, test changed headers, payloads, identifiers, and request sequences. Review generated middleware and handlers against the same requirements as manually written code.

Authentication: The First Line of Defense

Require appropriate authentication and authorization for sensitive operations. Some state-changing endpoints, such as public registration, intentionally accept unauthenticated requests and need controls suited to that purpose. HTTP method alone does not define the access policy.

Token-Based Authentication (JWT)

A bearer-token API can receive credentials in the Authorization header. The example below illustrates token extraction and verification, but is incomplete: configure the allowed algorithm, issuer and audience, validate required claims and key availability, and enforce authorization separately. A verified token does not by itself authorize an operation.

For more on securing these tokens, see our JWT security guide.

API Key Authentication

An API key can represent an application, service, or user depending on the system. Define its identity, scope, and allowed operations. Possessing a key does not grant permissions beyond the policy assigned to it.

API-key controls:

  • Generate high-entropy values for an application you control, using a cryptographic random source such as the API Key Generator.
  • For keys your service verifies, store a suitable verifier rather than the raw value where possible. Outbound provider keys must remain retrievable in protected secret storage.
  • Support revocation and rotation, and scope each credential to its intended use.
  • Record relevant usage without logging the secret key itself.

Validating API Input: Trust Nothing

Validate the inputs your application consumes, including relevant bodies, parameters, and headers. Apply size and resource bounds before costly parsing or processing.

Why Client-Side Validation Is Not Enough

Your frontend might validate that an email field contains a valid email address. But anyone can call your API directly with curl, Postman, or a custom script. Client-side validation is a user experience feature, not a security measure. If your backend assumes the data is "clean" because the frontend checked it, your app is vulnerable.

Schema Validation with Zod

Define expected input types, lengths, ranges, and allowed fields. The original Zod example below only demonstrates schema parsing: it omits authentication, authorization to assign roles, request-size limits, JSON-error handling, persistence, and a success response. A schema accepting an editor role does not authorize a caller to grant it.

SQL and Code Injection Prevention

Bind untrusted SQL values as parameters through the database driver or ORM. Where query structure must vary, choose identifiers and operators from an explicit allowlist; value parameters cannot replace every SQL element. Review ORM raw-query paths too. See injection prevention.

Rate Limiting and Resource Protection

Without rate limiting, an attacker can flood your API with requests. This can lead to Denial of Service (DoS), database exhaustion, or massive cloud bills.

Rate Limiting Strategies

Fixed Window

Count requests per time window (e.g., 100 requests per minute). Simple but allows bursts at window boundaries.

Sliding Window

Track requests over a rolling period to reduce fixed-window boundary bursts. The precise behavior depends on the algorithm and shared-state implementation.

Token Bucket

Each client gets a "bucket" of tokens that refill at a fixed rate. This allows for short bursts of legitimate activity while enforcing a strict average limit.

Per-Endpoint Limits

Choose limits from endpoint sensitivity, operation expense, expected traffic, and abuse scenarios. Combine appropriate account, tenant, and network controls; plan for distributed enforcement and legitimate users sharing an address. Test limits and failure behavior.

Authentication vs. Authorization (BOLA/IDOR)

Authentication establishes a caller’s identity. Authorization decides which actions that caller may perform on each resource. Missing object-level checks can allow access through a supplied identifier even when login succeeds.

For every resource operation, enforce the application’s actual access policy. Ownership may be part of that policy, alongside roles or shared access. The original comparison below assumes prior authentication middleware establishes the user; neither fragment is a complete application.

For more on this, check our broken access control checklist.

Secure Error Handling

Return useful, bounded errors without exposing secrets, stack traces, or unnecessary internal details. Keep protected diagnostic logs for investigation.

What to Redact

  • Stack traces: Keep internal traces out of production responses.
  • Database details: Avoid exposing unnecessary schema or engine information.
  • Internal paths: Do not disclose paths such as /var/www/html/....
  • Authentication errors: Use consistent responses where account existence is sensitive, and review timing and other side channels as well.

Consistent Error Format

Use consistent error formats and map internal exceptions to appropriate public responses. The helper below only formats a response; passing an internal exception message to it would still disclose that message.

Configuring CORS and Security Headers

CORS controls which cross-origin responses browser scripts may read, with preflight checks for some requests. It is not server authorization or a complete CSRF defense; some cross-origin requests can still be sent when the response is unreadable.

Production CORS Checklist

  • Public resources: Access-Control-Allow-Origin: * can be appropriate for non-credentialed public data.
  • Private responses: Allow only intended origins, such as https://myapp.com, rather than reflecting arbitrary input.
  • Methods: Configure preflight policy and enforce allowed methods and permissions on the server.
  • Credentials: Review Access-Control-Allow-Credentials with cookie behavior, explicit origins, and CSRF defenses.

Test your setup with our CORS tester or read our CORS explained guide.

Response Headers

Choose headers for the response type and threat model:

  • X-Content-Type-Options: nosniff: Restricts MIME sniffing in supported browser contexts; send the correct content type too.
  • X-Frame-Options: DENY: Restricts framing of relevant document responses.
  • Strict-Transport-Security: Instructs browsers that have learned the policy to use HTTPS for its lifetime; first-visit and preload behavior need separate consideration.
  • Cache-Control: no-store: Instructs compliant caches not to store the response; it does not prevent a recipient from copying data.

Logging and Monitoring

Record security-relevant events with enough context for investigation. Bound log volume, protect access and retention, and redact passwords, full credentials, and unnecessary personal data.

What to Monitor

  • Authentication and authorization failures: Investigate unexpected increases alongside normal traffic and deployment changes.
  • Resource-limit events: Review affected accounts and clients; a limit hit alone does not establish malicious intent.

API Security Review Checklist

Authentication

Enforced on every sensitive endpoint (no "forgotten" routes).

Input Validation

Schema-based validation for all request bodies and parameters.

Parameterized Queries

Bind untrusted values as parameters; allowlist any variable query structure.

Rate Limiting

Defined limits for auth, read, and write operations.

Authorization

Object-level checks (BOLA/IDOR prevention) on every resource access.

Generic Errors

No stack traces or internal metadata in responses.

CORS

Configured for intended browser response access, with server permissions enforced separately.

Security Headers

Review nosniff, HSTS, and X-Frame-Options for the relevant response types and browser behavior.

Secrets Management

Keep secret credentials out of source and client bundles. Use protected server-side secret storage; environment variables require correct build and runtime handling.

Logging

Audit trails for all state-changing requests.

Add Supported Automated Checks

SimplyScan’s URL scan checks supported public responses and assets for recognizable secret patterns, returned headers, and bounded anonymous API observations in about 30 seconds. It does not establish authentication correctness or test logged-in cross-user permissions.

Related Free Tools

Use these tools for their supported checks, then investigate the results:

  • JWT Debugger · Decode tokens and perform supported optional HMAC signature checks; decoding alone does not validate a token.
  • CORS Tester · Inspect returned CORS headers and preflight behavior for supplied inputs.
  • HMAC Generator · Generate or check supported signatures for supplied data; implement verification and replay controls in your webhook handler.
  • Security Headers Tool · Inspect returned response headers.

Browse all our free tools to harden your application today.

FAQ

What is an IDOR vulnerability and how do I prevent it?

IDOR occurs when a supplied identifier gives access without the required permission. In a URL, invoice_id=101 selects record 101; choosing a different identifier must not bypass authorization. An ownership check may compare authenticated_user_id with owner_id, but the policy may also include roles and sharing. Enforce the actual policy on the server.

Is client-side validation enough to secure my API?

No. A caller can bypass frontend checks using curl or another client. Validate the inputs the backend consumes, enforce size and resource limits, and apply authorization separately. Schema validation does not by itself make database queries or HTML output safe.

What rate limits should I set on my API endpoints?

Choose limits from operation expense, sensitivity, expected traffic, and abuse scenarios. Test account, tenant, and network limits with distributed traffic and legitimate shared addresses. A rate limiter reduces allowed request volume; it does not prevent every attack.

Why is wildcard CORS dangerous in production?

A wildcard such as Access-Control-Allow-Origin: * can be appropriate for non-credentialed public resources. Browsers reject wildcard origins for credentialed response access. Reflecting arbitrary origins while allowing credentials can expose private responses when cookies and other conditions permit. CORS does not replace authorization or CSRF defenses.

What should API error messages never reveal?

Avoid exposing secrets, stack traces, unnecessary schema details, and internal paths. Use consistent authentication errors where account existence is sensitive, but also examine timing and other side channels. Keep useful diagnostics in protected logs.

Are API keys the same as user authentication?

An API key may represent an application, service, or user according to the system’s design. Define its scope and enforce permissions for each operation. Use suitable storage, revocation, and rotation controls; user sessions can use cookies or tokens and do not inherently require JWTs.

These live figures describe all scanned sites. They do not establish prevalence for an AI-built subgroup, compare development methods, or attribute findings to AI generation.

30% of the 119 live sites SimplyScan has scanned (36 sites) have at least one high or critical security issue.

Frequently asked questions

What is an IDOR vulnerability and how do I prevent it?

IDOR occurs when a supplied identifier gives a caller access to a resource without the required permission. Check the relevant ownership, role, sharing, and operation rules on the server for every resource access. Authentication alone does not establish authorization.

Is client-side validation enough to secure my API?

No. A caller can bypass frontend checks and send a request directly. Validate the inputs the backend consumes, enforce size and resource limits, and apply authorization separately. A valid schema does not make a database query or HTML output safe by itself.

What rate limits should I set on my API endpoints?

Choose limits from operation expense, sensitivity, expected traffic, and abuse scenarios. Test account, tenant, and network limits with distributed traffic and legitimate shared addresses. A rate limiter reduces allowed request volume; it does not prevent every attack.

Why is wildcard CORS dangerous in production?

A wildcard can be appropriate for non-credentialed public resources. Browsers reject wildcard origins for credentialed response access. Reflecting arbitrary origins while allowing credentials can expose private responses when cookies and other conditions permit. CORS does not replace authorization or CSRF defenses.

What should API error messages never reveal?

Avoid exposing secrets, stack traces, unnecessary schema details, and internal paths. Use consistent authentication errors where account existence is sensitive, but also examine timing and other side channels. Keep useful diagnostics in protected logs.

Are API keys the same as user authentication?

An API key may represent an application, service, or user according to the system’s design. Define its scope and enforce permissions for each operation. Use suitable storage, revocation, and rotation controls; user sessions can use cookies or tokens and do not inherently require JWTs.

Related guides

All security guides · Free security tools · Platform scanners · Security checklist