Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to use @PreAuthorize

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)

like image 275
Anderson Rossi Avatar asked Jan 05 '16 15:01

Anderson Rossi


People also ask

What is the use of @PreAuthorize annotation?

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.

What's the difference between @secured and @PreAuthorize in Spring Security?

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 ... /></...> ).

How does @PreAuthorize work in spring boot?

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.

What is @PreAuthorize annotation in spring?

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);


1 Answers

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.

like image 126
Ankit Avatar answered Sep 25 '22 11:09

Ankit