java / beginner
Snippet
Restricting Service Method Execution with PreAuthorize
Spring Security allows declarative authorization directly on Java methods using the @PreAuthorize annotation with SpEL (Spring Expression Language) expressions. When a method is called, Spring intercepts the invocation, checks the caller's granted authorities, and denies execution if the required role is missing.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.stereotype.Service;@Servicepublic class AccountService {@PreAuthorize("hasRole('ADMIN')")public void deleteAccount(Long accountId) {System.out.println("Account deleted: " + accountId);}}
spring
Breakdown
1
@PreAuthorize("hasRole('ADMIN')")
Specifies that only users with the 'ROLE_ADMIN' authority can invoke the target method.
2
public void deleteAccount(Long accountId) {
The service method containing domain logic protected against unauthorized caller execution.