0 day streak
java / intermediate
Snippet

Custom Method-Level Authorization via SpEL Bean Evaluation

Spring Security's @PreAuthorize annotation supports Spring Expression Language (SpEL) referencing beans with '@beanName'. This encapsulates complex dynamic authorization logic into dedicated components rather than cluttering controllers or service methods.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Service
public class DocumentService {
@PreAuthorize("@documentSecurity.canAccess(#documentId, authentication)")
public Document getDocument(Long documentId) {
return findDocumentById(documentId);
}
}
@Component("documentSecurity")
public class DocumentSecurityChecker {
private final DocumentRepository repository;
public DocumentSecurityChecker(DocumentRepository repository) {
this.repository = repository;
}
public boolean canAccess(Long documentId, Authentication auth) {
if (auth == null || !auth.isAuthenticated()) {
return false;
}
return repository.isOwnerOrShared(documentId, auth.getName());
}
}
spring
Breakdown
1
@PreAuthorize("@documentSecurity.canAccess(#documentId, authentication)")
Invokes the 'canAccess' method on the 'documentSecurity' Spring bean before method execution, passing method arguments and context.
2
public boolean canAccess(Long documentId, Authentication auth)
Evaluates access rules programmatically using repository checks and the current principal's details.
3
return repository.isOwnerOrShared(documentId, auth.getName());
Checks whether the authenticated user owns or has received shared permissions for the specified document.