API Authentication vs. Authorization: Identity and Access
Understand API authentication and authorization, how they differ in request handling, and how to avoid common identity and access-control mistakes.
API authentication verifies the caller's identity, while authorization checks whether that identity may act on a particular resource. This guide follows the distinction through token validation, scopes, tenant and ownership checks, denial responses, caches, and background jobs, including ways a valid token can still expose another user's data. Use the examples and checklist to apply consistent policy to normal requests and less visible paths such as exports and queued work.
API Authentication vs. Authorization: Identity and Access
Introduction
An API can validate a caller’s access token and still expose another tenant’s record if a handler loads an object by ID without checking ownership. Authentication answers who is making the request; authorization answers whether that identity may perform this action on this resource. This guide follows both checks through tokens, tenant boundaries, cached responses, exports, and background jobs.
Identify the caller, then authorize the action
Authenticate callers when the API needs to distinguish users or services for protected actions, user-specific data, audit records, or caller-specific limits. For a browser app, a server-managed session cookie often makes revocation straightforward. OAuth or OIDC fits delegated user access and third-party clients; service credentials or mutual TLS fit workload-to-workload calls when each service needs a verifiable identity.
Authorize every non-public operation and resource lookup, even after the caller proves its identity. Roles or scopes work for broad capabilities; add ownership, tenant, or attribute checks when access depends on a particular record or context. A truly public, read-only endpoint can skip authentication, but it still needs abuse controls. Never treat a valid login or a broad role as permission to read every object.
Operational flow
flowchart TD
A[Client sends request] --> B[Validate contract and identity]
B --> C[Check permission and policy]
C -->|Allowed| D[Process and return documented result]
C -->|Denied| E[Return safe error]
D --> F[Record outcome without secrets]
Keep policy checks near protected operations
Put the decision near the boundary that owns it. Keep parsing, policy checks, and side effects visible in code review. For a policy change, review an example request and response alongside tests for an allowed request and a denied request. Keep external examples free of production data. Document behavior that clients need, while retaining private diagnostic detail in access-controlled logs.
Production failure scenarios and mitigations
- A stale token keeps a revoked role. A long-lived access token can preserve an old permission after an employee changes teams. Keep token lifetimes short or check current entitlements for sensitive actions, and test role changes.
- One object route skips the tenant check. A handler that loads a record by ID and trusts a broad
editorrole can expose another tenant’s data. Enforce tenant and ownership rules at the data boundary, then test cross-tenant requests. - A shared cache reuses another caller’s authorization result. If its key omits identity or permission context, a response allowed for one user may reach another. Include the relevant access context in the key or cache only public responses.
- A background job runs with broader access than its caller. An export queued by a user may later run under a privileged service account after that user’s access changes. Pass explicit actor and tenant context, then recheck policy when the job executes.
Authorization decision matrix
Start with the action the caller wants, then check the specific resource and context. A scope or role can grant the broad capability; it does not establish access to every object.
| Request | Capability check | Object or context check | Decision rule |
|---|---|---|---|
| Read one invoice | Token permits invoice reads | Invoice belongs to a tenant the principal may access; apply any ownership rule | Return only that invoice, or deny without its data. |
| Export a tenant’s invoices | Principal may export invoices | Resolve the tenant from verified membership and restrict the query to that tenant | Include only rows the principal is allowed to read. |
| Bulk update selected invoices | Principal may update invoices | Check every object ID and tenant before making changes | Follow a documented all-or-nothing or per-item contract; never skip the forbidden object check. |
| Serve a cached response | A fresh authorization decision allows the request | Cache key and invalidation preserve tenant, principal, and permission boundaries | Reuse only when the access context still matches, or cache public data only. |
| Run a queued export | The job type is permitted | Carry the requesting actor and tenant; recheck current policy when the worker runs | Do not let a privileged worker account silently inherit broader access. |
OAuth scope names are defined by the authorization server, so an API must define what each scope allows. For example, invoice:read can express a read capability, but the handler still needs an object-level check. OWASP recommends checking the requested action against the requested object on every endpoint that accepts an object ID. See the OAuth 2.0 scope definition and OWASP’s Broken Object Level Authorization guidance.
Worked request: invoice from another tenant
Assume the access token is valid for this API and identifies a user who belongs to tenant A. It also contains the API-defined invoice:read scope. The user requests an invoice ID that belongs to tenant B:
GET /tenants/tenant-a/invoices/inv-42
Authorization: Bearer <access-token>
Authentication passes: the token identifies the caller. The scope check also passes: this principal may read invoices in general. Authorization still fails because invoice inv-42 belongs to tenant B, and this caller has no membership or relationship that permits access to it. A handler that loads by invoice ID and returns the row after only checking invoice:read has a cross-tenant object authorization flaw.
Use server-verified identity and membership to constrain the lookup, then enforce any additional object relationship required by the product:
principal = validate_access_token(token)
require principal has scope invoice:read
invoice = find invoice where:
id = requested_invoice_id
tenant_id is in principal's verified tenant memberships
if no authorized invoice is found:
return the API's consistent denial response
else:
return the invoice
Do not treat tenant-a from the URL, a request header, or a body field as proof of membership. If users can switch between tenants, validate that selection against current server-side membership before using it. A 404 response can conceal whether an unauthorized invoice exists; a 403 makes the authorization failure explicit. Choose and document the response policy, and avoid returning invoice data or distinct error details to an unauthorized caller.
OWASP describes this class of flaw as manipulating an object identifier on an otherwise valid endpoint. The check must bind the authenticated principal, requested action, and loaded object; comparing one user ID with one URL parameter is not a general ownership policy.
Authorization test matrix
Test more than the happy path. Use different tenant IDs and resource IDs so a regression cannot pass because the fixture accidentally belongs to the caller.
| Test | Expected result |
|---|---|
| Tenant A reader requests an invoice owned by A | Return the invoice permitted by the product policy. |
| Tenant A reader substitutes an invoice ID owned by B | Deny with the chosen 403/404 policy; return no invoice data. |
| Tenant A caller has no invoice:read scope | Deny even when the invoice belongs to A. |
| Tenant A export includes or is pointed at B’s records | Export contains only authorized A records, or the request is denied. |
| Bulk update contains allowed A IDs and a forbidden B ID | No forbidden B record changes; behavior matches the documented atomic or per-item contract. |
| Tenant B requests a response cached for tenant A | Do not serve tenant A’s response. |
| A queued exporter’s access is revoked before the worker runs | Recheck policy at execution and do not produce the unauthorized export. |
For 403/404 choices, test both the response and the information it reveals. For bulk and export endpoints, verify every affected row or emitted record, not only the top-level HTTP status.
Observability checklist
- Track request volume, latency, status codes, and stable error categories by operation.
- Correlate failures with a request ID while keeping secrets out of logs.
- Monitor adoption, denial, validation, and retry trends relevant to this feature.
- Alert on anomalies and review dashboards after releases.
Security and Compliance Notes
Use TLS and least privilege. Do not trust client-supplied identity, ownership, or permission claims without verification. Keep credentials and sensitive payloads out of URLs, examples, analytics, and error messages. Apply the same server-side rules to alternate routes and batch operations. Watch for stale documentation, overly broad access, silent coercion, and tests that cover only successful requests.
Check every object lookup against the authenticated caller’s tenant and relationship to that object; a valid role alone does not prevent broken object-level authorization. Apply the same policy to nested resources, exports, bulk endpoints, and background jobs, where checks are easy to omit. If tokens carry roles or scopes, decide how quickly those claims must reflect revocation or role changes; long-lived tokens can preserve access after a policy update. Keep an audit trail of sensitive grants and denials with actor, action, resource identifier, and outcome, while excluding tokens and private resource data.
Validate tokens for the expected issuer, audience, type, signature, and time constraints before using their scopes or claims. Treat identity and tenant fields from request bodies or headers as untrusted unless they are bound to the verified principal. Keep audit events limited to the actor, action, target identifier, decision, and correlation context needed for review. Apply access and retention rules to those records, and confirm authentication and privacy requirements with the organization’s security, privacy, or compliance owner.
Common authorization mistakes
- Checking only that a token is signed. Also validate issuer, audience, intended token type, expiry, and required scopes or claims; a valid token for another service is not authorization for this API.
- Treating a scope as permission to every object. Scopes usually describe broad capabilities. Check tenant, ownership, and relationship rules for the specific resource and action.
- Trusting caller-supplied ownership or tenant fields. Derive the principal from verified credentials and bind resource access to server-side identity and data.
- Authorizing after a side effect. Check permission before writes, messages, exports, or other irreversible work, and recheck when a queued job executes.
- Returning inconsistent denial details. Choose a stable 403 or 404 policy so clients get predictable behavior and unauthorized callers cannot enumerate protected records.
- Testing only the allowed path. Include denied, cross-tenant, stale-claim, missing-resource, and alternate-route cases, using realistic claims and policy configuration.
Quick Recap Checklist
- Authenticate the caller before trusting identity claims.
- Authorize the requested action against the target resource.
- Check ownership or tenant boundaries on object-level operations.
- Return consistent denials without exposing protected data.
- Test allowed, denied, missing-resource, and cross-tenant requests.
Interview Questions
Authentication verifies the identity or credential presented by the caller. Authorization evaluates whether that verified identity may perform a particular action on a particular resource.
A role may grant a broad capability but not establish access to a specific tenant or object. Check ownership, tenant scope, and relevant relationships for the resource being requested.
Use a consistent 404 policy when revealing that a protected object exists would expose sensitive information. The trade-off is that clients cannot distinguish a hidden resource from a missing one.
No. The API should validate that the token is intended for it and then check its scopes or claims and the caller's permission for the specific resource and action.
Alternate execution paths can bypass checks placed only in a normal request handler. Apply the same tenant and resource policy wherever protected data is read or changed.
Record the actor, action, resource identifier, and outcome so access decisions can be investigated. Exclude tokens and private resource contents, and apply suitable access and retention controls to the audit data.
Choose a token lifetime that matches the revocation window the service can tolerate. For sensitive actions, check current entitlements or use a revocation mechanism so an old token cannot preserve access longer than policy allows.
A cache key that omits the caller, tenant, or permission context can reuse a response for someone who should not see it. Cache only public results or include the access context and invalidate entries when permissions change.
Enforce the rule on the server where the resource is selected or changed, using the authenticated caller and the resource’s tenant or ownership data. Test direct IDs, nested routes, exports, and bulk operations so alternate paths cannot skip the check.
Further Reading
- OWASP Authorization Cheat Sheet: Server-side checks, least privilege, and access-control testing.
- OWASP API Security: Broken Object Level Authorization: A common access-control failure in APIs.
- OAuth 2.0 and OIDC for Microservices: Token flows and identity validation across services.
- API Scopes, Roles, and Object-Level Permissions: Permission models and checks at resource boundaries.
Conclusion
Keep authentication and authorization separate in the request flow. Validate identity at the boundary, then check tenant, ownership, or other resource rules wherever protected data is accessed. Apply those checks to jobs and bulk paths too, and log the decision without recording credentials or private data. Next, work through API scopes, roles, and object-level permissions for more detailed permission models.
Category
Related Posts
Access Control Models and Least Privilege
Learn how DAC, MAC, RBAC, and ABAC control access, how least privilege limits damage, and how to review human and service permissions safely.
Injection and Broken Access Control: Practical Defenses
Learn why injection and broken access control happen, how parameterized queries and contextual encoding help, and how to verify object and action checks.
OAuth 2.0 and OIDC for Microservices
Learn how OAuth 2.0 and OpenID Connect enable delegated authorization and federated identity in microservices architectures.