0 day streak
java / beginner
Snippet

Role-Based Access Control with @PreAuthorize

Spring Security's @PreAuthorize annotation evaluates SpEL expressions before executing a method. In this example, access to listAllUsers() is restricted exclusively to authenticated users holding the 'ADMIN' role, preventing unauthorized endpoint execution.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
@RestController
@RequestMapping("/api/admin")
public class AdminController {
@GetMapping("/users")
@PreAuthorize("hasRole('ADMIN')")
public List<String> listAllUsers() {
return List.of("Alice", "Bob", "Charlie");
}
}
spring
Breakdown
1
@PreAuthorize("hasRole('ADMIN')")
Checks if the currently authenticated user possesses the 'ADMIN' role before allowing method execution.
2
public List<String> listAllUsers() {
Declares the protected endpoint method returning a list of user names.