0 day streak
java / intermediate
Snippet

Securing Domain Operations with Method-Level SpEL Expressions

Spring Security's `@PreAuthorize` annotation evaluates Spring Expression Language (SpEL) before executing the annotated method. It allows fine-grained access control by evaluating both current authentication details (`authentication.principal`) and target method arguments (`#document`), ensuring that users can only modify resources they own unless they hold administrative privileges.

snippet.java
java
1
2
3
4
5
6
7
8
@Service
public class DocumentService {
@PreAuthorize("hasRole('ADMIN') or #document.ownerId == authentication.principal.id")
public void archiveDocument(Document document) {
document.setStatus(DocumentStatus.ARCHIVED);
}
}
spring
Breakdown
1
@PreAuthorize("hasRole('ADMIN') or #document.ownerId == authentication.principal.id")
Defines an access rule evaluated prior to method execution, granting entry if the user is an admin or matches the document owner.
2
public void archiveDocument(Document document) {
Declares the business method accepting the document entity, exposing the `#document` variable to the SpEL context.