Reputation: 6537
I am trying to restrict access to my controller, based on user role. Now i can do that using the security.xml file in a following way
<http use-expressions="true">
<intercept-url pattern="/**" access="hasRole([ROLE_ADMIN,ROLE_USER])" />
</http>
But I dont want to do it this way. Rather i will write
<http use-expressions="true">
<intercept-url pattern="/**" access="isAuthenticated()"/>
</http>
and in the controller
@RequestMapping("/test")
@PreAuthorize("hasRole('ROLE_USER')")
public String test() {
return "test";
}
@RequestMapping("/testadmin")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String testAdminPage() {
return "testadmin";
}
now ROLE_USER can access both (ROLE_ADMIN & ROLE_ USER) tagged controller. this is the problem.
and based on this testadmin.jsp
can only be viewed by ROLE_ADMIN type user and test.jsp
can only be viewed by "ROLE_USER" type user.
To sum up rather than writing the access code in the xml file i want to control it from the controller.
How do i do this??
Upvotes: 3
Views: 1880
Reputation: 4239
you have to enable method level security via
<global-method-security pre-post-annotations="enabled"/>
then your spring controllers are going to get proxied and the PreAuthorize
annotation is going to be evaluated.
further information can be found here (section 16.3):
http://docs.spring.io/spring-security/site/docs/current/reference/el-access.html
EDIT:
I guess your Controller
beans are being created in the Disptacher Servlet (the web-context) and your security configuration is in the root-context -> Controllers will stay unaffected by the BeanPostProcessor
so you have to put the <global-method-security>
tag in the web context config (dispatcher-servlet.xml?)
Upvotes: 4