I'm using a custom access checker with @PreAuthorize:
@RestController
@RequestMapping("/users")
public class Users {
@PreAuthorize("@customAccessChecker.hasAccessToMethod('USERS', 'GET')")
@RequestMapping(method = RequestMethod.GET)
User getUsers() {
...
}
@PreAuthorize("@customAccessChecker.hasAccessToMethod('USERS', 'POST')")
@RequestMapping(method = RequestMethod.POST)
User addUser() {
...
}
}
I would like to get rid of the strings 'GET' and 'POST' in the @PreAuthorize annotation. Is it possible to get the RequestMethod used in the @RequestMapping as a variable input to hasAccessToMethod somehow?
I cannot remember an SpEL expression to get data from an annotation, but you can use SpEL to get the value from a parameter of your method with the #
character. Inject the HttpServletRequest
, it has a getMethod
method that contains what you want.
@PreAuthorize("@customAccessChecker.hasAccessToMethod('USERS', #request.method)")
@RequestMapping(method = RequestMethod.POST)
User addUser(HttpServletRequest request) {
// ...
}