I have a service class with secured methods (@PreAuthorize
, Spring Security).
Is Its bad practice coding?
Maybe should I use this annotation @PreAuthorize
only in my controller class (@Controller
or @RestController
)
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.
The real difference is that @PreAuthorize can work with Spring Expression Language (SpEL). You can: Access methods and properties of SecurityExpressionRoot . (Advanced feature) Add your own methods (override MethodSecurityExpressionHandler and set it as <global-method-security><expression-handler ... /></...> ).
Spring Security provides method level security using @PreAuthorize and @PostAuthorize annotations. This is expression-based access control. The @PreAuthorize can check for authorization before entering into method. The @PreAuthorize authorizes on the basis of role or the argument which is passed to the method.
The most obviously useful annotation is @PreAuthorize which decides whether a method can actually be invoked or not. For example (from the “Contacts” sample application) @PreAuthorize("hasRole('ROLE_USER')") public void create(Contact contact);
Yes, ideally, this type of authorization checks should be done at Controller or the first request handler step (like RestController which you mentioned). It makes more sense to put @PreAuthorize
annotation on Controller methods as request will not be forwarded to Service layer and unnecessary code (code which is there in controller method) will not be executed if correct role is not found.
BUT
If you have and application where service classes is being used by multiple controllers then you can have @PreAuthorize
annotation on Service layer. If tomorrow someone create a new controller(and forgets to use correct authorization checks) and use the existing service class then your application will handle the authorization correctly using service layer authorization.
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