Check resource ownership and tenant membership for each API operation. The examples separate the essential operation from the conditions a production implementation must enforce.
What It Does
Check resource ownership and tenant membership for each API operation.
Prerequisites
Use a dedicated development environment with test accounts and records. Separate authorization, validation and error handling from response formatting; never copy demonstration-only secrets into production.
Example 1: Core Behavior
The first example isolates the core operation so its result is easy to understand.
<?php
$actor = ['id'=>7, 'tenant'=>2]; $resource = ['owner'=>7, 'tenant'=>2];
$allowed = $resource['owner'] === $actor['id'] && $resource['tenant'] === $actor['tenant'];
http_response_code($allowed ? 200 : 403);
Example 2: Alternative or Failure Case
The second example demonstrates an alternative outcome, rule or failure condition.
<?php
$actor = ['id'=>3,'tenant'=>9]; $resource = ['owner'=>3,'tenant'=>4];
if ($actor['tenant'] !== $resource['tenant']) { http_response_code(404); exit; }
echo 'Tenant matched';
Practical Example: Applying the Rule
The practical example shows how to carry the same constraint into application code.
<?php
$roles=['editor']; $required='admin';
if (!in_array($required,$roles,true)) { http_response_code(403); echo json_encode(['error'=>'Forbidden']); exit; }
Important Behavior and Edge Cases
Never rely solely on a user ID supplied in the request path or JSON body.
Comparison with Related Functions or Patterns
| Approach | When it differs |
|---|---|
| Writing Authorization Checks for API Resources | Check resource ownership and tenant membership for each API operation. |
| Related API or pattern | A database query constrained by current tenant can enforce isolation in depth. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Trusting a user ID supplied by a client without checking resource scope | Never rely solely on a user ID supplied in the request path or JSON body. |
| Substituting a related API without checking its semantics | A database query constrained by current tenant can enforce isolation in depth. |
Key Takeaways
- Check resource ownership and tenant membership for each API operation.
- Never rely solely on a user ID supplied in the request path or JSON body.
- A database query constrained by current tenant can enforce isolation in depth.
Select this API or pattern based on its documented behavior and the trust boundaries in your own application, and test all external integrations against their actual deployments.