Inherit @PreAuthorize annotation with custom annotation for spring custom method security expression

Viewed 805

I have successfully implemented a Custom Method Security expression in my Spring Boot project.

Here is my expression root:

public class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

    public boolean checkTwoParamsAreEqual(Long param1, Long param2){
        return param1.equals(param2);
    }

    //constructor and overridden methods ignored for brevity

}

All other required configuration and handlers for method security expression is implemented correctly.

Inside my controller class, I did:

@GetMapping("/test")
@PreAuthorize("checkTwoParamsAreEqual(#id1, #id2)")
public String tst( @RequestParam("id1") Long id1, @RequestParam("id2") Long id2){
   return "Voila!!!";
}

With this, when I make get request with the same value for id1 and id2 request params, it returns Voila!!!, and for different request parameter values, it throws 403 exception. This is exactly what I want.


Now, I want to optimize my above code by using a custom annotation class for @PreAuthorize.

My custom annotation is defined as:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
@PreAuthorize("checkTwoParamsAreEqual(#id1, #id2)")
public @interface PreCheckParamsAreEqual {
}

And, I updated my controller by:

@GetMapping("/test")
@PreCheckParamsAreEqual
public String tst( @RequestParam("id1") Long id1, @RequestParam("id2") Long id2){
   return "Voila!!!";
}

With this change, no matter what values I pass for request parameters id1 and id2, they always return "Voila!!!". I could not figure out a way on how I can create a custom annotation with parameters.

0 Answers
Related