0 day streak
java / beginner
Snippet

Restricting Endpoint Access with PreAuthorize

Using Spring Security's @PreAuthorize annotation allows evaluation of authorization expressions before invoking a controller method, ensuring only users with the required role can proceed.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
@RestController
@RequestMapping("/api/admin")
public class AdminController {
@PreAuthorize("hasRole('ADMIN')")
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
return ResponseEntity.noContent().build();
}
}
spring
Breakdown
1
@PreAuthorize("hasRole('ADMIN')")
Evaluates a SpEL expression to ensure the authenticated user has the ADMIN authority prior to method execution.
2
@DeleteMapping("/users/{id}")
Maps incoming HTTP DELETE requests with a dynamic path variable to this handler method.
3
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
Defines the method signature and binds the URL template variable {id} to the method argument.
4
return ResponseEntity.noContent().build();
Returns an HTTP 204 No Content status code indicating successful deletion with an empty body.