mosab
mosab

Reputation: 207

Can I use @PreAuthorize in a simple class ( not a @Component)

I am trying to add control authorization in some methods using @PreAuthorize("hasRole('ADMIN')").

Methods belong to a simple class DaoImpl implementing an interface DAO, I add this

@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) to my security config class.

for me it doesn't work, is it logic or I miss something?

Upvotes: 0

Views: 407

Answers (1)

Toerktumlare
Toerktumlare

Reputation: 14820

The answer is no.

Spring can only enforce annotations on classes it is aware of. To make spring aware of instantiated classes it needs to either instantiate them itself, which means the class needs to be annotated with one of springs lifecycle annotations ex. @Component, @Service @RestController, or you need to instantiate them yourself and hand them over to the spring context. This can for instance be done by using the new keyword in a @Bean annotated function in a @Configuration annotated class and then return the newly created class from the @Bean annotated function.

If you create the class yourself by using the new keyword just randomly in your application, spring will have no awareness of the class and hence has no ability to intercept function calls using spring AOP and in turn enforce annotations on them like for instance @PreAuthorize

Upvotes: 1

Related Questions