javaspringspring-mvcspring-security

Is there a way to access a PathVariable in a controller level @PreAuthorize annotation?


is there a way to access the httpRequest within a controller level @PreAuthorize annotation to obtain a PathVariable and use it for the expression inside the @PreAuthorize annotation?

I want to be able to do the following, where #somePathVariable would result in the actual value passed for the PathVariable:

@RequestMapping(value = "/{somePathVariable}/something")
@PreAuthorize("@someBean.test(#somePathVariable)")
public class SomeController { ... }

It also would be sufficient if i could access the HttpServletRequest and get the PathVariable manually.

Please note that this expression is at the controller level before answering. I'd appreciate any help!


Solution

  • In new spring (6.x.x) you have to compile java with "-parameters" option.
    That option solved my problem getting path parameter from request.
    See that post for more details.
    So code like this will work:

    @PreAuthorize("#n == authentication.name")
    Contact findContactByName(@Param("n") String name);