Request Authorization and Filter Chains¶
Security objective¶
Authenticate a caller when required, then decide whether that identity may access a requested resource. Public routes are explicit exceptions, not the default.
HTTP semantics¶
- 401 Unauthorized: valid authentication is missing or invalid.
- 403 Forbidden: authentication exists, but authority is insufficient.
- 200-class response: request passed the boundary; business rules may still deny an operation.
Spring Security model¶
FilterChainProxy owns a list of SecurityFilterChain instances. It selects the first chain whose securityMatcher matches the request. Chains are not merged.
Inside the selected chain, AuthorizationFilter evaluates request rules in declaration order. A broad rule placed before a narrow rule can make the narrow rule unreachable.
| Responsibility | Spring API |
|---|---|
| Select a chain | FilterChainProxy, securityMatcher |
| Define policy | authorizeHttpRequests |
| Match a request | requestMatchers |
| Require identity | authenticated() |
| Require role/authority | hasRole, hasAuthority, AuthorizationManager |
| Hold current identity | SecurityContext |
hasRole("ADMIN") normally checks for ROLE_ADMIN; hasAuthority compares the exact value.
Trust and failure cases¶
- Overlapping chains select an unintended policy.
- Matcher ordering exposes a restricted route.
- A forwarded header creates an untrusted principal.
- Request authorization is mistaken for object ownership authorization.
- Anonymous and insufficient-authority failures are conflated.
Request rules should be complemented by method or domain authorization when a resource can be reached through multiple protocols or code paths.
Design scenario: one API, different access by role¶
Status: Theory. The complete ADMIN/MANAGER/USER policy below is a design exercise, not an implemented lab. Existing runnable examples cover ADMIN/USER route checks in apps/rest-api and owner-or-admin document access in TenantObjectService, but not this three-role matrix.
Requirement¶
Design an employee API where administrators have full access, managers have partial access, and users have limited access. Define those terms before selecting annotations:
| Operation | ADMIN | MANAGER | USER |
|---|---|---|---|
GET /employees | All employees in the caller's tenant | Employees in managed teams | Own employee record only |
GET /employees/{id} | Any employee in the caller's tenant | Managed-team members and self | Self only |
PATCH /employees/{id} | Approved editable business fields | Team scheduling fields for managed-team members | Own contact preferences only |
DELETE /employees/{id} | Allowed within tenant, subject to retention rules | Denied | Denied |
| Change roles or team ownership | Separate privileged workflow | Denied | Denied |
Here, ADMIN means tenant administrator, not unrestricted cross-tenant access. Full access does not bypass retention, audit, or other business invariants. If platform-wide administration is required, model it separately.
Spring API mapping and design¶
- Validate authentication and derive roles, tenant, and subject from the trusted security context, never from caller-supplied role headers or request fields.
- Use HTTP-method-aware
requestMatchersfor coarse operation permissions. Use service-level@PreAuthorizewith a policy bean for tenant, team, ownership, and operation checks. Method security must be enabled, and calls must pass through the Spring proxy. - For collection reads, constrain the repository query to the caller's authorized tenant and row scope before pagination and counting. Do not fetch everything and filter the response afterwards.
- Use explicit response DTOs: an administrator, manager, and user need not see the same fields. Document these representations using OpenAPI schemas; do not serialize persistence entities directly.
- Validate PATCH fields against an operation-specific allowlist. Reject forbidden fields such as
roles,tenantId,ownerId, or salary rather than trusting a hidden UI control or unrestricted entity binding. - Define multi-role behavior explicitly. If roles are additive, combine permitted capabilities within the tenant boundary; do not rely on role ordering or assume
ADMINautomatically inheritsMANAGERandUSER. Spring requires explicit policy or a configured role hierarchy.
Failure modes and acceptance criteria¶
A future executable lab must prove:
- Missing, malformed, or expired credentials produce 401 under the API's authentication contract.
- Authenticated callers without permission receive 403; an intentional 404 concealment policy, if chosen for object reads, is applied consistently.
- Administrators can perform approved operations only inside their tenant.
- Managers cannot access another team's records by changing an ID, including through batch endpoints.
- Users cannot read another employee or update forbidden fields on their own record.
- Collection results, counts, pagination, exports, and response fields do not disclose unauthorized data.
- Multiple-role callers follow the documented capability-combination policy.
- Direct service calls through the Spring proxy enforce the same policy as HTTP calls.
Related interview and design questions¶
| Scenario | Key design question |
|---|---|
| Approval workflows | Can a manager approve their own expense? Combine RBAC with separation of duties. |
| Multi-tenant SaaS | Can an administrator cross tenant boundaries? Enforce tenant scope independently of role. |
| Field-level authorization | Can a user PATCH their role or salary? Prevent mass assignment on writes and sensitive-field leakage on reads. |
| Temporary delegation | Can a substitute manager act for a week? Validate scope, expiry, revocation, and the original actor. |
| Role revocation | What happens to an already-issued JWT after demotion? Define an acceptable stale-authorization window and revocation strategy. |
| Bulk operations and exports | What if a batch mixes authorized and unauthorized IDs? Define atomic rejection versus safe per-item results without leaking records. |
| Concurrent changes | What if team membership changes during an update? Define transaction and consistency boundaries for authorization. |
| Support access | How is emergency access approved, time-limited, audited, and prevented from becoming a permanent bypass? |
Continue with LAB-001 for existing request-level checks and LAB-027 for the existing tenant/object authorization example. Neither lab implements the complete three-role scenario above.
Transfer¶
FastAPI dependencies and Node/Nest middleware or guards solve the same boundary problem. First-match chain selection, SecurityContext, and Spring authorization DSL behavior are Spring-specific.
Continue with LAB-001.