Describe how to implement dynamic access-control policies in Spring Security.

Dynamic access-control policies evaluate authorization rules at runtime rather than relying on static role checks, typically using Spring Expression Language inside @PreAuthorize or @PostAuthorize to reference live data such as method arguments, the current user, or database-backed permissions.

Key Points: • SpEL expressions in @PreAuthorize can reference method parameters directly, e.g. #userId == authentication.principal.id. • @PostAuthorize can inspect the returned object after method execution to decide whether to allow it, useful for ownership checks. • Custom PermissionEvaluator implementations let you plug in database-driven or business-specific permission logic. • Roles or attributes can be fetched dynamically at evaluation time rather than being hardcoded, supporting attribute-based access control (ABAC). • This trades some performance and readability for flexibility, so it's best reserved for genuinely context-dependent rules rather than simple role checks.

Example: A document-sharing app uses @PreAuthorize("@docPermissionEvaluator.canEdit(#docId, authentication)") to check, at runtime, whether the current user has been granted edit rights on that specific document by looking it up in the database.

Code Example:

@PreAuthorize("@docPermissionEvaluator.canEdit(#docId, authentication)")
public void editDocument(Long docId, String content) {
    // edit logic
}

Interview Tip: A concise interview answer is:

"I'd use SpEL inside @PreAuthorize or @PostAuthorize to evaluate access rules at runtime, referencing method parameters or a custom PermissionEvaluator bean that checks permissions dynamically, often against a database. This supports attribute- or resource-based access control beyond simple static roles."