Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

API Security Complete Checklist

By Kokil Thapa | Last reviewed: September 2026

An API Security Complete Checklist turns vague "make it secure" requests into concrete controls you can verify before production. APIs sit at the centre of modern apps—mobile clients, partner integrations, payment callbacks, and admin dashboards all depend on them. One broken endpoint can leak customer data, bypass billing, or let an attacker pivot into your database. I've shipped and maintained REST APIs on Laravel and Symfony production systems for legal-tech portals, eCommerce carts, and booking platforms since 2010. This checklist reflects what actually fails in the wild—not textbook theory.

What belongs in an API Security Complete Checklist?

Think of API security as layers, not a single switch. Transport encryption, identity, access control, data handling, and observability each address different attack paths. Skipping one layer—say, strong auth but no rate limiting—leaves you open to credential stuffing and enumeration.

A practical checklist groups controls by lifecycle stage: design, build, deploy, and operate. Design covers threat modelling and least-privilege scopes. Build covers validation, auth middleware, and safe error responses. Deploy covers TLS, firewall rules, and secret rotation. Operate covers logging, alerting, and patch cadence.

API Security LayersMonitoring and Incident ResponseData Validation and Output EncodingAuthentication and AuthorizationTransport Security (TLS 1.2+)Network Perimeter and GatewayInternet-facing clients
Layered API security model used in a complete production checklist—from TLS through auth to monitoring.

On client portals I've built—document upload, payment collection, role-based dashboards—the highest-risk endpoints are always the same: login, password reset, file download, admin mutations, and webhook receivers. Prioritise those in your checklist first.

For a deeper OWASP mapping, see the companion guide on OWASP API Top 10 mitigations. Pair it with Laravel API best practices if your stack is PHP.

Checklist categories at a glance

  • Identity: OAuth 2.0, JWT, API keys, mTLS—pick per client type.
  • Access control: object-level and function-level authorization on every route.
  • Input: schema validation, type coercion guards, size limits.
  • Output: no stack traces, filter fields by role, paginate large collections.
  • Transport: HTTPS only, HSTS, secure cookies where applicable.
  • Operations: audit logs, anomaly alerts, dependency scanning, backup restore tests.

How do you authenticate and authorize API requests securely?

Authentication proves who is calling. Authorization proves they may perform the action on that specific resource. Confusing the two is the most common API security failure I see on production Laravel apps.

Public mobile and SPA clients should use short-lived access tokens with refresh rotation. Server-to-server integrations fit API keys or OAuth client credentials. Never embed long-lived secrets in mobile binaries—they will be extracted.

Laravel 12 and 13 projects typically choose between Sanctum and Passport. Sanctum suits first-party SPAs and token-based mobile auth. Passport fits full OAuth2 server scenarios with third-party clients. Both require you to enforce scopes and token expiry in middleware—not only at login.

Laravel Sanctum token example

// routes/api.php — protect every mutating route
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
    Route::get('/cases/{case}', [CaseController::class, 'show']);
    Route::post('/cases/{case}/documents', [DocumentController::class, 'store']);
});

// CasePolicy.php — object-level authorization
public function view(User $user, LegalCase $case): bool
{
    return $user->id === $case->client_id
        || $user->hasRole('staff');
}

Register policies and call $this->authorize() in controllers. Middleware alone is not enough. An authenticated user must not read another user's case file by changing an ID in the URL—that is Broken Object Level Authorization (BOLA), OWASP API #1.

JWT-based APIs need extra care. Store signing keys outside the repo. Rotate keys on schedule. Validate aud, iss, and exp on every request. Read common JWT vulnerabilities before shipping. For OAuth flows, follow OAuth security best practices—use PKCE for public clients and never accept tokens via query string.

AuthN and AuthZ FlowClientAPI GatewayRate limit + TLSAuth ServiceToken issueResource API1. Request + token2. Validate token3. Policy check4. Filtered responseReject: invalid token, wrong scope,or BOLA on object ID
Every API request should pass gateway checks, token validation, and object-level authorization before returning data.

Authorization checklist items

  1. Define roles and scopes in code—not only in documentation.
  2. Test horizontal privilege escalation: user A must not access user B's records.
  3. Test vertical escalation: customer tokens must not hit admin routes.
  4. Invalidate tokens on password change and role revocation.
  5. Log denied authorization attempts with correlation IDs.

How do you protect APIs against the OWASP API Top 10?

The OWASP API Security Top 10 (2023) remains the industry baseline for API threat classification. Map each item to a concrete control in your checklist—not a vague "we use HTTPS."

OWASP RiskWhat breaksChecklist control
API1 BOLAID tampering exposes other users' dataPolicy checks on every object; use UUIDs; never trust client-supplied owner IDs
API2 Broken AuthenticationWeak login, leaked tokensMFA for admin; short TTL; refresh rotation; lockout after failed attempts
API3 Broken Object Property AuthMass assignment changes role fieldsAllow-lists in Form Requests; separate admin DTOs from public serializers
API4 Unrestricted Resource ConsumLarge payloads, deep paginationRate limits; max page size; query cost limits; timeouts
API5 Broken Function Level AuthAdmin routes exposed to usersRoute groups by role; deny by default
API6 Unrestricted Business FlowsCoupon stacking, booking abuseServer-side workflow rules; idempotency keys on payments
API7 SSRFURL fetch hits internal servicesBlock private IP ranges; allow-list outbound domains
API8 Security MisconfigurationDebug on, CORS wildcardDisable debug in prod; strict CORS; security headers
API9 Improper InventoryShadow endpoints in prodOpenAPI spec; deprecate old versions; gateway route audit
API10 Unsafe ConsumptionTrusting third-party API responsesValidate upstream JSON; TLS verify; timeout and circuit breaker

On eCommerce APIs I've maintained, API6 shows up as double-discount abuse and cart manipulation. Fix it with server-side price recalculation at checkout—not client-trusted totals. Payment endpoints should use idempotency keys so retries do not double-charge.

Legal-tech portals add document-handling risk. File upload endpoints need MIME verification, size caps, virus scanning where budget allows, and storage outside the web root. Download URLs should be signed and expire quickly. The Mijar Law Associates client portal pattern—authenticated uploads with role-scoped access—is representative of what production legal APIs require.

OWASP API Top 10 to ControlsAccess RisksBOLA, BFLA, Property AuthFix: Policies + scopesAPI1, API3, API5Abuse RisksResource, Business FlowsFix: Rate limits + rulesAPI4, API6Config RisksMisconfig, InventoryFix: Hardening + versioningAPI8, API9Trust RisksAuth, SSRF, UpstreamFix: Validate all inputsAPI2, API7, API10
Group OWASP API Top 10 risks into four control families for a scannable API Security Complete Checklist.

How should you validate input and rate-limit API endpoints?

Never trust client JSON. Validate structure, types, lengths, and enums on the server with explicit schemas. In Laravel, Form Request classes beat inline validation—they keep controllers thin and give you one place to audit rules.

// StoreDocumentRequest.php
public function rules(): array
{
    return [
        'title' => ['required', 'string', 'max:120'],
        'file'  => ['required', 'file', 'mimes:pdf,jpg,png', 'max:5120'],
        'case_id' => ['required', 'uuid', 'exists:cases,id'],
    ];
}

Return generic 422 validation errors to clients. Log detailed context server-side only. Attackers probe validation messages to map your schema.

Rate limiting belongs at the gateway and application layer. Laravel's built-in throttle middleware is a start. Production systems also need IP-based limits on login, token issuance, and search endpoints. Compare gateway options in the Kong vs Traefik vs AWS API Gateway guide if you terminate traffic upstream.

Rate limit configuration example

// AppServiceProvider boot() — Laravel 12+
RateLimiter::for('login', function (Request $request) {
    return Limit::perMinute(5)->by($request->ip());
});

RateLimiter::for('api', function (Request $request) {
    return Limit::perMinute(120)->by(
        $request->user()?->id ?: $request->ip()
    );
});

Payment and webhook endpoints need different limits—too aggressive and legitimate gateway retries fail; too loose and brute force succeeds. Document limits in your public API docs. Use the JSON formatter tool to inspect payload shapes during security reviews.

Symfony 8.1 APIs follow the same principles via the security firewall and validator components. See Symfony security firewall configuration for route-level access rules on PHP 8.4.1+ projects.

How do you secure API keys, secrets, and transport in production?

Secrets live in environment variables or a vault—not in Git, not in frontend bundles, not in Postman collections shared in Slack. Rotate keys when staff leave and after any suspected leak. Generate strong random secrets with a password generator during provisioning, then store them in your secrets manager.

TLS is non-negotiable. Terminate HTTPS at your load balancer or reverse proxy. Enforce TLS 1.2 minimum. Enable HSTS. Redirect plain HTTP to HTTPS. Certificate renewal via Let's Encrypt should be automated—I handle this routinely on Ubuntu 22/24 servers with Certbot.

CORS is not authentication. A misconfigured Access-Control-Allow-Origin: * on cookie-authenticated routes creates real risk. Allow-list exact origins. Keep credentials mode strict.

Production hardening checklist

  • APP_DEBUG=false in all production environments.
  • Disable unused HTTP methods—most APIs need GET, POST, PUT/PATCH, DELETE only.
  • Set security headers: X-Content-Type-Options, X-Frame-Options, CSP where feasible.
  • Run API workers as non-root OS users—see Ubuntu server security best practices.
  • Keep PHP 8.3+ or 8.5, Laravel 12/13, and Composer 2.10 dependencies patched.
  • Commit no .env files; scan repos with gitleaks or similar in CI.

Deploy through CI/CD with lint and test gates. Several sites I maintain use Deployer 7 with GitLab CI—build artefacts exclude secrets, and PHP-FPM reloads after symlink swap to clear opcache. Broken deploy paths in cron jobs are a recurring ops issue; they are also a security issue when old code keeps running.

Production Deploy SecurityGitLab CILint + testsBuild ArtefactNo secrets insideDeployer 7Zero downtimeTLS EdgeShared .env + vault secretsDB creds, API keys, JWT signing keysPHP-FPM reload + opcacheInvalidate stale bytecode after deployFail deploy if debug on or TLS cert expired
Production API security extends from CI gates through secret storage to TLS and post-deploy PHP-FPM reload.

API versioning reduces breach blast radius when you must ship breaking auth changes. Maintain a deprecation calendar. Document sunset headers. Read API versioning strategies compared and building RESTful APIs with Laravel for URL and header patterns that do not strand legacy clients unexpectedly.

How do you monitor, log, and respond to API security incidents?

You cannot defend what you cannot see. Structured logs beat unstructured printf debugging. Every API request should carry a correlation ID from gateway to application to database query log.

Log authentication failures, authorization denials, validation errors on sensitive fields, rate-limit hits, and admin actions. Do not log passwords, full credit card numbers, or raw bearer tokens. Redact PII per your retention policy—especially relevant for GDPR-aware systems discussed in broader compliance work.

Metrics and alerts close the loop. Track 401/403 spikes, 5xx rates, latency p99, and queue depth. Prometheus and Grafana work well for self-hosted stacks—see API monitoring with Prometheus and Grafana. Set alerts on anomaly thresholds, not only on total downtime.

Incident response steps for API teams

  1. Contain: revoke compromised tokens, rotate keys, block abusive IPs at the gateway.
  2. Assess: trace correlation IDs; identify affected users and data classes.
  3. Fix: patch vulnerability; add missing authorization check; deploy via normal CI.
  4. Notify: inform stakeholders per legal and contractual obligations.
  5. Review: update the checklist; add regression tests; schedule tabletop exercise.

Third-party integrations—payment gateways like eSewa, Khalti, Stripe—need webhook signature verification. Never process a callback without validating HMAC or certificate pinning per provider docs. Timeouts and retry backoff prevent cascade failures when upstream APIs degrade.

API Incident ResponseDetectContainInvestigateRecoverAudit logs + correlation IDs + gateway metricsRevoke tokens, rotate secrets, patch codeUpdate API Security Complete ChecklistAdd regression tests and runbook entry
API security incidents should flow from detection through containment to checklist updates and new regression tests.

Schedule regular checklist reviews—quarterly minimum for high-risk APIs handling payments or personal documents. After Laravel or PHP upgrades, re-run authorization tests. Dependency scanners (composer audit) belong in CI alongside your unit and feature tests. Engage testing and optimization services when you need an external pass before a major launch.

For ongoing patch management and server hardening, support and maintenance contracts beat heroic firefighting. APIs are long-lived products; security is continuous, not a one-time gate.

Key Takeaways

  • Treat the API Security Complete Checklist as a living document—update it after every incident, upgrade, and new integration.
  • Enforce object-level authorization on every endpoint; authentication alone prevents almost nothing.
  • Map controls directly to OWASP API Top 10 risks so gaps are visible during code review.
  • Rate-limit login, token, and search routes; validate all input with explicit server-side schemas.
  • Keep secrets out of Git, enforce TLS everywhere, and log with correlation IDs minus sensitive data.
  • Automate dependency audits and deploy checks in CI—manual pre-release scans get skipped under deadline pressure.

People Also Ask

What is the most common API security vulnerability?

Broken Object Level Authorization (BOLA) tops the OWASP API list. Attackers change resource IDs in URLs or JSON bodies and access other users' records. Fix it with server-side policy checks on every object—not by hiding IDs.

Should API keys go in environment variables?

Yes. Store keys in environment variables or a dedicated secrets vault on the server. Never commit them to Git or embed them in frontend JavaScript. Rotate keys on a schedule and immediately after staff changes or suspected leaks.

How often should you review an API security checklist?

Review before every major release and at least quarterly for production APIs. Also review after dependency upgrades, new third-party integrations, and any security incident—no matter how small the blast radius appeared.

Is HTTPS enough to secure an API?

HTTPS encrypts traffic in transit, but it does not stop authorization bugs, injection, or credential theft. You still need strong auth, access control, input validation, rate limiting, and monitoring. TLS is one layer in the full checklist—not the whole solution.

Build your next API on a security-first foundation

The API Security Complete Checklist is not paperwork—it is the difference between a portal that survives real traffic and one that leaks data on the first ID enumeration attempt. Start with your highest-risk routes, automate what you can in CI, and treat every production API as a product that needs ongoing maintenance. If you want help auditing an existing Laravel API or designing a new integration layer, contact us to discuss scope—or explore API development services and relevant work in the portfolio.

Frequently Asked Questions

It covers authentication, authorization, input validation, rate limiting, TLS, secret management, OWASP API Top 10 mitigations, logging, and incident response—verified before every production release and after dependency upgrades.

Broken Object Level Authorization (BOLA) tops the OWASP API list. Attackers change resource IDs in URLs or JSON bodies and access other users' records. Authentication alone does not stop this. Fix it with server-side policy checks on every object access—register Laravel policies, call authorize() in controllers, and test horizontal privilege escalation. Never rely on hiding or obscuring IDs.

Yes. Store keys in environment variables or a vault—not Git, frontend bundles, mobile binaries, or Postman collections shared in Slack. Rotate when staff leave or after any suspected leak.

Think in layers and lifecycle stages. Design covers threat modelling and least-privilege scopes. Build covers validation, auth middleware, and safe error responses. Deploy covers TLS, firewall rules, and secret rotation. Operate covers logging, alerting, and patch cadence. Categories include identity, access control, input, output, transport, and operations. Prioritise login, password reset, file download, admin mutations, and webhook receivers first.

Authentication proves who is calling; authorization proves they may perform the action on that specific resource. Confusing the two is the most common failure on production Laravel apps. Public mobile and SPA clients need short-lived access tokens with refresh rotation. Server-to-server integrations fit API keys or OAuth client credentials. Middleware alone is not enough—every route needs object-level authorization so user A cannot read user B's records by changing an ID.

On Laravel 12 and 13 projects, Sanctum suits first-party SPAs and token-based mobile auth. Passport fits full OAuth2 server scenarios with third-party clients. Both require enforcing scopes and token expiry in middleware on every mutating route—not only at login. Whichever you pick, define roles and scopes in code, invalidate tokens on password change, and log denied authorization attempts with correlation IDs.

Map each OWASP API Security Top 10 (2023) risk to a concrete checklist control—not vague claims like "we use HTTPS." BOLA needs policy checks on every object. Broken authentication needs MFA for admin, short TTL, and lockout after failed attempts. Mass assignment needs allow-lists in Form Requests. Resource consumption needs rate limits and max page sizes. Business flow abuse needs server-side workflow rules and idempotency keys on payments.

Never trust client JSON. Validate structure, types, lengths, and enums on the server with explicit schemas. In Laravel, Form Request classes keep controllers thin and give one auditable place for rules. Return generic 422 validation errors to clients; log detailed context server-side only—attackers probe validation messages to map your schema. Apply rate limiting at both gateway and application layers, with separate tuning for login, token issuance, search, payment, and webhook endpoints.

The article example configures login at 5 requests per minute per IP and general API traffic at 120 per minute per authenticated user or IP. Payment and webhook endpoints need their own limits—too aggressive and legitimate gateway retries fail; too loose and brute force succeeds.

Secrets live in environment variables or a vault—not Git, frontend bundles, or shared collections. Rotate keys when staff leave and after suspected leaks. TLS is non-negotiable: HTTPS only, TLS 1.2 minimum, HSTS enabled, plain HTTP redirected. Set APP_DEBUG=false, allow-list exact CORS origins, add security headers, disable unused HTTP methods, and run API workers as non-root OS users. Keep PHP 8.3+ or 8.5, Laravel 12 or 13, and Composer 2.10 dependencies patched.

No. CORS is not authentication. A misconfigured Access-Control-Allow-Origin wildcard on cookie-authenticated routes creates real risk. Allow-list exact origins and keep credentials mode strict. Authentication, token validation, and object-level authorization must still run on every request regardless of what CORS headers permit.

On client portals with document upload, payment collection, and role-based dashboards, the highest-risk endpoints are always the same: login, password reset, file download, admin mutations, and webhook receivers. File uploads need MIME verification, size caps, and storage outside the web root. Download URLs should be signed and expire quickly. Audit these before lower-traffic read-only routes.

Every API request should carry a correlation ID from gateway to application to database. Log authentication failures, authorization denials, validation errors on sensitive fields, rate-limit hits, and admin actions. Do not log passwords, full credit card numbers, or raw bearer tokens. On incident: contain by revoking tokens and rotating keys; assess via correlation IDs; fix and deploy through normal CI; notify stakeholders; then update the checklist and add regression tests.

Never process a callback from eSewa, Khalti, Stripe, or any third-party gateway without validating HMAC signatures or certificate pinning per provider docs. Payment endpoints should use idempotency keys so retries do not double-charge. Apply rate limits tuned for legitimate gateway retry behaviour. On eCommerce APIs, recalculate prices server-side at checkout—never trust client-supplied totals—to prevent cart manipulation and double-discount abuse.

Treat it as a living document—update after every incident, upgrade, and new integration. Schedule quarterly reviews minimum for high-risk APIs handling payments or personal documents. After Laravel or PHP upgrades, re-run authorization tests. Run composer audit in CI alongside unit and feature tests so manual pre-release scans do not get skipped under deadline pressure.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: