Part of our Security & Cybersecurity series
Read the complete guideAPI Security 2026: Authentication & Authorization Best Practices (OWASP Aligned)
APIs are the attack surface. Modern businesses expose more API endpoints than web pages. Attackers know this, and the OWASP API Security Top 10 is a clinical list of what they exploit: broken authorization, broken authentication, excessive data exposure, and unrestricted resource consumption. This guide is what we implement on the ECOSIRE platform and advise clients to implement.
TL;DR
- Authentication 2026 baseline: OAuth 2.1 + PKCE for public clients, workload identity (SPIFFE/mTLS) for service-to-service, passkeys for user-facing flows.
- JWT is fine if you do it right: rotate signing keys, use short TTLs, keep a revocation list for sensitive tokens, prefer PASETO or Branca for new greenfield systems.
- Authorization requires a policy engine. RBAC alone is insufficient at mid-market scale. ABAC + OPA (Open Policy Agent) or Google's Zanzibar-style relationship-based access control are the serious options.
- Rate limiting is a security control, not a performance tweak. Apply at edge, per-user, and per-tenant simultaneously.
- Audit every authorization decision, not just denies. You cannot triage an incident without the full trace.
OWASP API Top 10 2023 refresher
The current list (OWASP revised in 2023, still operative for 2026) is our north star:
- API1: Broken Object Level Authorization (BOLA). Most common. Attackers increment object IDs to read others' data.
- API2: Broken Authentication. Weak login, session, token issuance, or token validation.
- API3: Broken Object Property Level Authorization. Mass assignment, excessive data exposure.
- API4: Unrestricted Resource Consumption. No rate limits, no request size caps, no timeouts.
- API5: Broken Function Level Authorization. Admin endpoints exposed to regular users.
- API6: Unrestricted Access to Sensitive Business Flows. Voucher abuse, inventory scraping, mass signup.
- API7: Server Side Request Forgery (SSRF). API fetches user-supplied URL without validation.
- API8: Security Misconfiguration. CORS wildcards, debug endpoints, default credentials.
- API9: Improper Inventory Management. Zombie APIs, unversioned endpoints, forgotten test instances.
- API10: Unsafe Consumption of APIs. Trusting upstream APIs without validation.
Notice that 5 of the 10 (API1, API3, API5, API6, API10) are fundamentally authorization issues. Authorization is harder than authentication; budget accordingly.
Authentication
OAuth 2.1
OAuth 2.1 consolidates best practices from the 2.0 era and retires unsafe grants:
- Authorization Code + PKCE is the required flow for public clients (SPAs, mobile apps).
- Implicit flow is removed.
- Resource Owner Password Credentials (ROPC) is removed.
- Bearer tokens must travel only in Authorization headers, never query strings.
- Refresh tokens must be rotated for public clients; sender-constrain via DPoP or mTLS for sensitive use.
Use a real identity provider (Auth0, Okta, Keycloak, Authentik, WorkOS, Ory Hydra). Do not build your own OAuth server.
PASETO vs JWT
JWT is the incumbent and fine if you avoid the foot-guns:
- Always specify the algorithm on the verifier side. Never trust the
algheader (classicalg: noneand algorithm confusion attacks). - Use asymmetric signing (RS256, EdDSA/Ed25519). HS256 forces the verifier to share the signing secret.
- Rotate keys regularly using a key ID (
kid) and a JWKS endpoint. - Short TTLs (5-15 minutes for access tokens, refresh tokens rotated per use).
- Keep a revocation mechanism for high-risk tokens.
PASETO (Platform-Agnostic Security Tokens) fixes JWT's ergonomics by locking the algorithm to the version:
v4.publicis Ed25519;v4.localis XChaCha20-Poly1305. No algorithm negotiation.- Typed versions prevent algorithm confusion attacks by construction.
- Similar structure to JWT (header.payload.footer).
- Use for greenfield systems or where algorithm agility is a risk.
Branca is another option — a token format based on IETF XChaCha20-Poly1305. Simpler than JWT or PASETO.
Rotating keys
Signing keys should rotate at least quarterly. The pattern:
- Generate new key pair. Publish new public key in JWKS with
kid=v2. - Start signing new tokens with
kid=v2. - Verifiers accept both
kid=v1andkid=v2for the remaining TTL of in-flight v1 tokens (typically 30-60 minutes). - Remove
v1from JWKS after TTL expiry plus a safety window (24 hours).
Automate this; manual rotation gets skipped.
Passkeys (WebAuthn)
Passkeys (FIDO2 resident keys) are production-ready in 2026 across all major browsers and OSes. For user-facing authentication:
- Register a passkey after first password login. Makes future login passwordless.
- Allow multiple passkeys per user (work laptop, personal phone, hardware key).
- Keep a secondary recovery method. Lost-device scenarios are the #1 support ticket.
- Enforce
userVerification: 'required'to ensure biometric or PIN. - Store the credential ID + public key, not any secret.
Passkeys eliminate phishing of credentials. They do not eliminate session hijack; combine with short session TTLs and device binding.
Authorization
RBAC (Role-Based Access Control)
RBAC is the minimum. Users have roles (admin, manager, member, viewer). Roles grant permissions (orders:read, orders:write). Permissions map to API operations.
RBAC breaks down when:
- Different tenants need different role definitions.
- A user can edit only orders they own, not all orders.
- A permission depends on object state (cannot refund a settled invoice).
ABAC (Attribute-Based Access Control)
ABAC evaluates attributes of the subject (user), object (resource), action (operation), and environment (time, IP, risk score) against policy rules.
# OPA policy: allow refund if user is support + invoice not settled
package api.refunds
default allow := false
allow if {
input.user.role == "support"
input.action == "refund"
input.resource.type == "invoice"
input.resource.status != "settled"
input.resource.tenantId == input.user.tenantId
}
OPA (Open Policy Agent)
OPA is the de facto standard for externalized policy. Your API calls OPA with a decision request, OPA evaluates the relevant Rego policies, OPA returns allow/deny plus obligations.
Advantages:
- Policy as code, reviewable in git.
- Centralized, consistent across microservices.
- Unit-testable (OPA has a built-in test framework).
- Audit-friendly (every decision is traceable).
Performance: OPA evaluates typical policies in sub-millisecond time. Run it as a sidecar or library (Go, Rust, WASM bindings).
Zanzibar-style ReBAC
Google's Zanzibar introduced relationship-based authorization: the canonical model for large-scale, fine-grained permissions (Google Drive, YouTube, etc.). Production implementations: SpiceDB (AuthZed), OpenFGA (Auth0/Okta), Warrant.
Use case: "user:alice has reader role on document:q1-report, which is contained in folder:finance, which is owned by group:finance-team, which has admin role granted to user:alice." Transitively, alice can write.
Pick Zanzibar-style when:
- You have deeply nested resource hierarchies (folders, teams, projects).
- Sharing semantics matter ("anyone with the link can view").
- Millions of permission checks per second.
OPA + ReBAC can coexist: OPA for coarse policy, ReBAC engine for fine-grained relationship lookups.
Rate limiting
Rate limits are a defense-in-depth security control:
- Block credential stuffing (attempts per IP, per username).
- Block enumeration (list endpoints, search endpoints).
- Block DoS (expensive endpoints like PDF export, AI inference).
- Block business logic abuse (coupon redemption, trial signup, password reset).
Token bucket algorithm
Classic algorithm. Each user has a bucket of tokens; each request consumes one; bucket refills at a fixed rate. Burst capacity = bucket size.
Layer your limits
Apply at multiple levels simultaneously:
| Layer | Limit target | Example |
|---|---|---|
| Edge (CDN/WAF) | Per IP | 1,000 req/min per IP |
| API gateway | Per API key | 10,000 req/min per key |
| Application | Per user | 60 req/min per user for search |
| Endpoint | Per user per endpoint | 5 req/min for password reset |
| Tenant | Per tenant | 100 req/sec per tenant in multi-tenant SaaS |
Use Redis-backed counters (INCR with EXPIRE) or a dedicated library (Upstash Ratelimit, Cloudflare Rate Limiting Rules). Return 429 Too Many Requests with a Retry-After header.
Secrets management
- No secrets in code or env files committed to git. Use AWS Secrets Manager, HashiCorp Vault, Doppler, or 1Password Secrets Automation.
- Rotate quarterly or automatically on scope change.
- Short-lived credentials wherever possible. IAM roles for EC2. Workload identity for Kubernetes. Service account tokens with 15-minute TTLs.
- Secret scanning in CI:
trufflehog,gitleaks, or GitHub's built-in secret scanning. - Break-glass recovery plan. If your secret manager is down, how do you authenticate? Document it.
Audit logging
Log every authentication event and every authorization decision (allow and deny):
{
"ts": "2026-04-24T10:15:22Z",
"event": "authz.decision",
"user": { "id": "u_123", "tenant": "acme", "roles": ["support"] },
"action": "refund",
"resource": { "type": "invoice", "id": "inv_8842", "tenant": "acme" },
"decision": "allow",
"policy": "refunds.allow_support_unsettled",
"request_id": "req_abc",
"source_ip": "1.2.3.4"
}
Ship to an immutable store (CloudWatch Logs with no-delete IAM, SIEM with retention policy, or append-only log like AWS CloudTrail Lake). Retain per compliance regime (SOX 7 years, PCI 1 year, GDPR per data category).
Zero-trust network
Assume breach. Never trust the network:
- mTLS for service-to-service. SPIFFE IDs in a service mesh (Istio, Linkerd) issue short-lived workload certs.
- No default allow. Every service-to-service call requires explicit authorization.
- Egress filtering. Prevent compromised services from exfiltrating data to attacker-controlled domains.
- Device trust. For admin APIs, require device certificates or a managed-device check.
Top 10 common mistakes (and the fix)
- IDOR via sequential IDs. Use UUIDs or ULIDs for resource IDs, never integers. Always verify the caller owns the resource server-side, regardless of ID format.
Authorization: Bearerlogged to APM. Strip the header from traces; APM configs often capture it by default.- Returning user objects with password hashes. Use explicit DTO mappers, never return entity objects.
- CORS wildcards in production.
Access-Control-Allow-Origin: *with credentials is impossible (spec forbids), but devs often set it and disable credentials for "simplicity." Use an allowlist. - Client-side role checks only. The UI can hide the button; the API must still reject the call.
- Trusting JWTs from unknown issuers. Verify
iss,aud,exp,nbf. Reject tokens where any claim is missing. - SSRF in webhook endpoints. Validate user-provided URLs: no private IPs, no localhost, no link-local, enforce HTTPS in prod.
- Password reset without token binding. Reset tokens must be single-use, expire in 15 minutes, and invalidate on password change.
- Unrestricted file upload. Validate MIME type + magic bytes + file size + filename. Store in object storage with restrictive policies, never on the API filesystem.
- Missing rate limit on signup. Attackers create 10,000 free-tier accounts per hour for abuse (coupons, SMS send, AI inference). Rate-limit signup per IP and per email domain.
FAQ
1. OAuth 2.0 or OAuth 2.1? OAuth 2.1 for new work. It is a consolidation of 2.0 best practices, not a breaking change. Most identity providers support both.
2. Do I need to migrate from JWT to PASETO? No, not urgently. A well-implemented JWT is secure. Migrate if your threat model includes algorithm confusion attacks or if you want to reduce the surface of cryptographic agility.
3. How do I handle API key authentication for server-to-server? Prefer workload identity (mTLS, SPIFFE) or OAuth client credentials. If you must use API keys: long random string, HMAC-signed requests, rotate every 90 days, never log the key.
4. Should I use Passkeys for B2B APIs? Passkeys are for user authentication. For B2B API clients (other backends calling yours), use OAuth client credentials or mTLS, not passkeys.
5. What is a reasonable rate limit for a public search API? 30-60 requests per minute per user, with bursts of 10-20. Tune by watching your logs — real users rarely exceed 10/min; bursts above 60 are bots.
6. How often should I run a pen test? Annually minimum, plus after any major architectural change. Continuous automated scanning (Burp, ZAP in CI) catches the low-hanging fruit between human tests.
Talk to our security team
We run API security audits, OWASP-aligned threat models, and policy engine rollouts (OPA, SpiceDB) for regulated industries. We also build license, auth, and authorization systems end-to-end. Start at /contact?source=blog&topic=api-security, or see our Odoo implementation services if your API sits behind an ERP.
Written by
ECOSIRE TeamTechnical Writing
The ECOSIRE technical writing team covers Odoo ERP, Shopify eCommerce, AI agents, Power BI analytics, GoHighLevel automation, and enterprise software best practices. Our guides help businesses make informed technology decisions.
ECOSIRE
Grow Your Business with ECOSIRE
Enterprise solutions across ERP, eCommerce, AI, analytics, and automation.
Related Articles
Authentik OIDC/SSO: Complete Integration Guide
Complete Authentik OIDC and SSO integration guide: OAuth2 provider setup, Next.js callback handling, NestJS JWT validation, user provisioning, and production configuration.
ERP Data Migration: Best Practices and Common Pitfalls
A complete guide to ERP data migration. Covers data extraction, cleaning, transformation, loading, validation, and the common pitfalls that derail migrations.
JWT Authentication: Security Best Practices in 2026
Secure your APIs with JWT best practices: RS256 vs HS256, HttpOnly cookies, token rotation, refresh patterns, and common vulnerabilities to avoid in 2026.
More from Security & Cybersecurity
Cybersecurity for E-commerce: Protect Your Business in 2026
Complete ecommerce cybersecurity guide for 2026. PCI DSS 4.0, WAF setup, bot protection, payment fraud prevention, security headers, and incident response.
Cybersecurity Trends 2026-2027: Zero Trust, AI Threats, and Defense
The definitive guide to cybersecurity trends for 2026-2027—AI-powered attacks, zero trust implementation, supply chain security, and building resilient security programs.
AI Agent Security Best Practices: Protecting Autonomous Systems
Comprehensive guide to securing AI agents covering prompt injection defense, permission boundaries, data protection, audit logging, and operational security.
Cloud Security Best Practices for SMBs: Protect Your Cloud Without a Security Team
Secure your cloud infrastructure with practical best practices for IAM, data protection, monitoring, and compliance that SMBs can implement without a dedicated security team.
Cybersecurity Regulatory Requirements by Region: A Compliance Map for Global Businesses
Navigate cybersecurity regulations across US, EU, UK, APAC, and Middle East. Covers NIS2, DORA, SEC rules, critical infrastructure requirements, and compliance timelines.
Endpoint Security Management: Protect Every Device in Your Organization
Implement endpoint security management with best practices for device protection, EDR deployment, patch management, and BYOD policies for modern workforces.