I am trying to get a @PreAuthorized annotation on a controller class to work in conjunction with a @PreAuthorized annotation on methods (endpoints) of the same class. The overview of the class looks something like this:
@RestController
@RequestMapping("/api")
@PreAuthorized("hasRole('CLASS_LEVEL_ROLE')")
public class foo {
@GetMapping("/test")
@PreAuthorized("hasRole('METHOD_LEVEL_ROLE')")
@Timed
public ResponseEntity<String> bar() {
return ResponseEntity.ok().body("entered method successfully");
}
}
Currently what is happening is only the method level annotation is being taken into account.
Ideally what would happen is only users with role 'CLASS_LEVEL_ROLE' and 'METHOD_LEVEL_ROLE' would be allowed access to bar().
I'm aware I could use
@PreAuthorized("hasRole('CLASS_LEVEL_ROLE') and hasRole('METHOD_LEVEL_ROLE')")
but I have some controllers where all endpoints would have to have the same 'CLASS_LEVEL_ROLE' and it would be more convenient to have a generalized class annotation.
@PreAuthorize allows a class level annotation. The way it is supposed to work is that if a method level annotation exists, it will override the class level annotation. You can't do a union of both. So a class level annotation can be seen as a fallback when a method level annotation is not present.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With