java / intermediate
Snippet
Method-Level Security with @PreAuthorize
@PreAuthorize allows for fine-grained access control using Spring Expression Language (SpEL). You can restrict methods based on user roles or compare method arguments with the current authenticated user.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
@Servicepublic class AdminService {@PreAuthorize("hasRole('ADMIN')")public void deleteSensitiveData(Long id) {// Logic to delete data}@PreAuthorize("#username == authentication.name")public void updateProfile(String username, ProfileData data) {// Logic to update profile}}
spring
Breakdown
1
hasRole('ADMIN')
SpEL expression checking if the authenticated user has the 'ADMIN' authority.
2
#username == authentication.name
Compares the method parameter 'username' with the name of the currently logged-in user.
3
@PreAuthorize
Annotation that triggers a security check before the method is actually executed.