I have a situation where i need to pass the path variable as a argument to the preauthorize
@RequestMapping(value="/page/{cmd}", method = RequestMethod.GET)
@PreAuthorize("hasRole(#cmd)")
public void method(@PathVariable String cmd, HttpServletRequest request, HttpServletResponse response){
// my stuff
}
It is not working.can anyone suggest me how to use the path variable in pre authorize please.
Add a Interceptor. Register the Interceptor. With this you will be able to read the @PathVariable by the name you have given to the pathvariable for all the request made. Save this answer.
Simply put, the @PathVariable annotation can be used to handle template variables in the request URI mapping, and set them as method parameters. Let's see how to use @PathVariable and its various attributes.
@PathParam is a parameter annotation which allows you to map variable URI path fragments into your method call. @PathVariable is to obtain some placeholder from the URI (Spring call it an URI Template) Follow this answer to receive notifications.
The @PreAuthorize annotation checks the given expression before entering the method, whereas the @PostAuthorize annotation verifies it after the execution of the method and could alter the result.
Spring Security's @PreAuthorize
is used for authorizing access to methods. It doesn't know really much about Spring MVC, in particular about its @RequestMapping
annotation.
Names like #cmd
will refer to method parameters, and your cmd
parameter is null. Change it to:
@PathVariable("cmd") String cmd
This way, cmd
path variable will be bound to cmd
method parameter, which will then be bound by #cmd
in @PreAuthorize
.
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