Protect Backend APIs¶
Use this page when your app has backend routes, server actions, or API resources that should only be available to signed-in or authorized callers.
Hiding a button in the UI is not protection. The backend must enforce access at the resource boundary.
API Protection Flow¶
Build one reusable guard implementing steps 1-6: extract the bearer token, validate signature/issuer/audience/expiry/tenant/scopes/subject type, map claims to the app's user and permission model, check the specific resource, return safe errors, and log request ID, tenant ID, subject ID, and reason class without secrets.
Reuse the validation helper from verify-tokens.md or quickstart-backend-api.md instead of writing new validation logic.
Apply the guard to every backend route, server action, and resource boundary, not just the obvious ones.
- Extract the bearer token from the
Authorizationheader. - Validate signature, issuer, audience, expiry, tenant or workspace, scopes, and subject type.
- Map validated claims to your app's user, workspace, role, or permission model.
- Check the specific resource being requested.
- Return a safe error if validation or authorization fails.
- Log request ID, tenant ID, subject ID, and reason class without logging secrets or raw tokens.
What To Check On Each Route¶
| Route type | Check |
|---|---|
| User profile | Subject matches the profile or has an allowed admin role. |
| Workspace data | Token tenant or workspace matches the resource tenant or workspace. |
| Admin action | Token has the required scope and subject type. |
| Billing or security action | Require stronger assurance when your app policy needs it. |
| Agent or tool call | Distinguish human, delegated, and agent subjects. |
Scope Design¶
Use scopes that describe API actions:
| Scope | Example meaning |
|---|---|
projects:read |
Read project resources. |
projects:write |
Create or modify project resources. |
billing:read |
View billing data. |
admin:write |
Perform sensitive administrative changes. |
Avoid one broad scope for every route. Broad scopes make access review and incident response harder.
Reject These Requests¶
Exercise each protected route with every case in this list: missing or malformed bearer tokens, wrong issuer or environment, wrong audience, another tenant or workspace, missing required scopes, wrong subject type, and requests for resources the subject should not access.
Every case must be rejected with a safe error before any data is served; add these cases to the project's test suite.
- missing or malformed bearer tokens
- tokens from the wrong issuer or environment
- tokens without the expected audience
- tokens from another tenant or workspace
- tokens missing required scopes
- tokens with the wrong subject type
- requests for resources the subject should not access
For low-level protocol details, use Reference: OAuth And OIDC.