java / beginner
Snippet
Restricting Method Access by User Role Using PreAuthorize
The @PreAuthorize annotation evaluates a Spring Expression Language (SpEL) expression before invoking a method. It denies invocation and throws an AccessDeniedException if the current authenticated principal lacks the required role.
snippet.java
java
1
2
3
4
5
6
7
8
@Servicepublic class UserService {@PreAuthorize("hasRole('ADMIN')")public void deleteUserAccount(Long userId) {System.out.println("Admin deleted user with ID: " + userId);}}
spring
Breakdown
1
@Service
Marks the class as a service layer component in the Spring context.
2
@PreAuthorize("hasRole('ADMIN')")
Checks if the authenticated user has the 'ROLE_ADMIN' authority before allowing the method to run.
3
public void deleteUserAccount(Long userId) {
Executes sensitive deletion logic only when authorization check succeeds.