4

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?

maxo
  • 97
  • 9

1 Answers1

6

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) {
    // ...
}
kagmole
  • 2,005
  • 2
  • 12
  • 27
  • it's a sane answer. Since an annotation value expects a constant Spring, you can't concatenate it with some enum value. – Andrew Tobilko Jun 15 '17 at 08:01
  • From the request I could also get the resource name using #request.servletPath, instead of using the hardcoded 'USERS' string. – maxo Jun 15 '17 at 11:05