I'm trying to create my own method security expressions, that I want to use in @PreFilter and @PostFilter annotations.
Searching for tutorials and similar questions I've found two ways to proceed.
The first is to extend DefaultMethodSecurityExpressionHandler and override createSecurityExpressionRoot, in order to give a customized SecurityExpressionRoot.
@PreAuthorize('isOwner(#someEntity)') 
The second way is to simply use a @Component class and in @Pre / @Post filter accessing its methods with @bean.method()
@PreAuthorize("@mySecurityService.isOwner('#someEntityl')")
My question is: Which is the preferred way? If both are ok, why choose one ore another?
thank you Marco
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.
hasAuthority(...) checks the content WITHOUT a prefix, i.e. just the pure content. Follow this answer to receive notifications.
The difference between @Secured and @PreAuthorize are as follows : The main difference between @Secured and @PreAuthorize is that @PreAuthorize can work with Spring EL. We can access methods and properties of SecurityExpressionRoot while using @PreAuthorize but not with @Secured.
Method-level security is implemented by placing the @PreAuthorize annotation on controller methods (actually one of a set of annotations available, but the most commonly used). This annotation contains a Spring Expression Language (SpEL) snippet that is assessed to determine if the request should be authenticated.
Advantages of @PreAuthorize('isOwner(#someEntity)') way over @bean.method() way:
CustomSecurityExpressionRoot.isOwner() then it is clear for you (and even for some new developer familiar with Spring Security) that you need to review all @Pre / @Post annotations. This advantage is not so important if you have JUnit tests for all @Pre / @Post cases.@bean.method() way, for example @sec.isOwner())SecurityExpressionRoot you automatically have access to authentication, trustResolver, roles, permissionEvaluator ojects. It is not so important because you can easy get them in your custom bean too.Advantages of @bean.method() way over @PreAuthorize('isOwner(#someEntity)') way:
I am like your @bean.method() way. IMHO all differences are not so important (for my previous project). But I like "easy setup" option so much! So for next project I'll try your @bean.method() way in conjuction with JUnit tests for all @Pre / @Post cases.
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