What could be the problem ? When I use this annotation in my controller, it works fine, the page is only accessible for a ROLE_USER
@Secured("ROLE_USER")
This annotation works also :
@PreAuthorize("hasRole('ROLE_USER')")
When I move the same annotation to my Service, it doesn't work, the method is accessible without having the ROLE_USER role !! I'm testing Spring Security, My Service is just a test (TestService interface and its implementation), whether I put the annotation in the interface or in the implementation level, as if the annotation doesn't exist.
This is my dispatcher-servlet.xml file :
<security:global-method-security secured-annotations="enabled" pre-post-annotations="enabled"/>
<bean id="TestService" class="myPackage.TestServiceImpl"/>
Thanks for helping
As @M. Deinum said , the problem is that your enable-global-method-security
is only in the DispatchereServlet's context, but not in the ContextLoaderListener's (which is a parent of the other one). Your service beans probably belong to ContextLoaderListener context, and your controllers to DispatchereServlet. As @M. Deinum mentioned , @Secured
and @PreAuthorize
are AOP based and work only withing the same context where enable-global-method-security
is.
TL;DR Add sec:enable-global-method-security
to ContextLoaderListener's context (might be a param called contextConfigLocation
in your web.xml).
I had the exact similar problem and I have solved by injecting the Service/Component/Repository.
I have a working example here: https://github.com/lfoppiano/spring-security-j2ee-preauth-example
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.