Implementing Authorization Logic
1. Implementing Role-Based Access Control (RBAC)
| Concept | Detail |
|---|---|
| User | Has roles |
| Role | Has permissions |
| Permission | Action on resource type |
| Decision | Has user role with permission? |
Example: Spring Security check
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(UUID id) { ... }
2. Implementing Attribute-Based Access Control (ABAC)
| Element | Detail |
|---|---|
| Subject attrs | Department, clearance |
| Resource attrs | Owner, classification |
| Action attrs | Read, write, approve |
| Environment attrs | Time, IP, MFA status |
| Policy engine | OPA, Cedar, XACML |
3. Designing Permission Checking Logic
Example: Permission service
public boolean canEdit(UserId actor, OrderId order) {
var o = orderRepo.findById(order).orElseThrow();
return o.ownerId().equals(actor) || rbac.hasRole(actor, "ADMIN");
}
4. Implementing Resource-Level Authorization
| Pattern | Detail |
|---|---|
| Ownership check | Resource has owner field |
| Tenant scoping | Filter by tenant ID always |
| ACL | Per-resource grants |
| Spring | @PostAuthorize("returnObject.ownerId == authentication.name") |
5. Using Authorization Annotations
| Annotation | Use |
|---|---|
@PreAuthorize | Before method, full SpEL |
@PostAuthorize | After method, inspect result |
@PreFilter/@PostFilter | Filter collection elements |
@Secured | Simple role check |
@RolesAllowed | JSR-250 standard |
6. Implementing Policy-Based Authorization
Example: OPA Rego policy
package orders.allow
default allow = false
allow {
input.action == "read"
input.user.tenant == input.resource.tenant
}
allow {
input.action == "delete"
"admin" in input.user.roles
}
7. Implementing Hierarchical Roles
Example: Role hierarchy (Spring)
@Bean
RoleHierarchy roleHierarchy() {
var h = new RoleHierarchyImpl();
h.setHierarchy("""
ROLE_SUPERADMIN > ROLE_ADMIN
ROLE_ADMIN > ROLE_USER
""");
return h;
}
8. Handling Dynamic Permissions
| Source | Detail |
|---|---|
| Database | Mutable; cache with TTL |
| Feature flag | Per-user/tenant overrides |
| Admin UI | Grant/revoke at runtime |
9. Implementing Method-Level Security
| Step | Detail |
|---|---|
| Enable | @EnableMethodSecurity |
| Apply | Service-layer methods |
| Why service | Catch all entry points (web, MQ, jobs) |
10. Implementing Claim-Based Authorization
Example: JWT claim check
@PreAuthorize("authentication.principal.claims['scope'].contains('orders:write')")
public Order place(...) { ... }
11. Implementing Permission Caching
| Concern | Strategy |
|---|---|
| Hot reads | Caffeine local cache |
| TTL | 1-5 min for permissions |
| Invalidation | On role change event |
| Negative cache | Cache "denied" briefly |
12. Implementing Authorization Audit Trail
| Field | Detail |
|---|---|
| timestamp | UTC |
| actor | User ID + tenant |
| action | Verb + resource |
| decision | ALLOW / DENY |
| reason | Policy/rule that fired |
| request context | IP, correlation ID |