Reputation: 523
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
)
Upvotes: 9
Views: 4394
Reputation: 575
Normally I use @PreAuthorize/@PostAuthorize on Service Layer and <sec:intercept-url
or javaconfig
to check the roles for Controllers/Urls.
If you have to check something inside the data/object(like if user has permission for changing data from one specific company) you should check in the Service Layer.
Upvotes: 0
Reputation: 3183
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.
Upvotes: 11