Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should spring security method level annotations be applied at the controller layer or the service layer?

I have been using spring security with @PreAuthorize on my controller methods. My reasoning was that I wanted the authorization check to happen predictably in one layer, and as early as possible in the request. However, I just read the spring security 3 documentation, and saw that they recommend applying method level security on the service layer (but they don't say why).

My question is: should spring security method level annotations be applied at the controller layer or the service layer? (Or "both", or "it depends"?) More importantly: why?

like image 934
Jason Avatar asked Jan 31 '13 13:01

Jason


People also ask

Which annotation can be used with in Spring Security to apply method level security?

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.

Which annotation provides the method level security for the Spring beans but only based on the roles?

The @Secured annotation is used to specify a list of roles on a method. So, a user only can access that method if she has at least one of the specified roles.

How does Spring Security authentication work internally?

The Spring Security Architecture There are multiple filters in spring security out of which one is the Authentication Filter, which initiates the process of authentication. Once the request passes through the authentication filter, the credentials of the user are stored in the Authentication object.


1 Answers

"It depends" :). If your application has a service layer through which all your business logic is applied then that is usually a clean place to apply your security constraints and be certain that you haven't missed out any corner cases.

Web code is generally messier, there's more of it, it changes more rapidly and you may end up calling the same service methods from multiple places. Someone might add a new controller and forget to secure it properly. Alternatively you might have different types of clients calling the same services.

But it depends on how your application is structured and what your use cases are. You may have a good argument for why you want to secure a controller.

like image 188
Shaun the Sheep Avatar answered Oct 09 '22 08:10

Shaun the Sheep