Dynamic authorization with Spring Security @PreAuthorize¶
Dynamic authorization in Spring Security can be implemented by delegating access control logic to a custom Spring Bean using the @PreAuthorize annotation.^[001-TODO__code-getway.md]
Implementation Strategy¶
The core technique involves using a SpEL (Spring Expression Language) expression within the annotation, typically formatted as @BeanName.methodName(arguments).^[001-TODO__code-getway.md] This syntax invokes a specific method on a managed bean to determine authorization.^[001-TODO__code-getway.md] For instance, @PreAuthorize("@reportSecurityValidator.hasAuthority(#reportType)") checks permissions by passing a method parameter (#reportType) to the validator logic.^[001-TODO__code-getway.md]
Custom Validator Logic¶
The referenced bean must contain a public method returning a boolean to grant or deny access.^[001-TODO__code-getway.md] Inside this validator, custom logic can access the SecurityContextHolder to retrieve the current Authentication object and the associated principal (often a custom UserDetails implementation).^[001-TODO__code-getway.md]
This allows for complex, data-driven rules, such as comparing the user's granted authorities against a specific attribute of the domain object being accessed.^[001-TODO__code-getway.md] The validator returns true if the user possesses the required authority and false otherwise.^[001-TODO__code-getway.md]
Example Use Case¶
A common scenario is controlling access to API resources based on dynamic resource types. In a reporting system, the ReportType enumeration can define specific permission strings (e.g., proxy:domain:edit) corresponding to different resources.^[001-TODO__code-getway.md] The controller endpoint extracts the resource type from the request, and the @PreAuthorize annotation ensures the user has the specific authority associated with that particular type before execution proceeds.^[001-TODO__code-getway.md]
Related Concepts¶
- Spring Security
- [[SpEL]]
Sources¶
^[001-TODO__code-getway.md]