Reputation: 910
I have been working on Spring security since a year. Today I faced a minor problem regarding Authorization in Spring Security
For intercept url I have configured my spring-security.xml like this
<intercept-url method="GET" pattern="/groups" access="hasRole('VIEW_GROUPS')" />
<intercept-url method="GET" pattern="/admin" access="hasRole('VIEW_ADMIN')" />
This might happen that a user has no role to see /groups page so in that case how can I make sure that user is automatically redirected to /admin page?
I know answer would be simple but I got stuck here.
Upvotes: 0
Views: 4501
Reputation: 5512
You could make the redirect in the access denied handler.
Usually you will have something like this in your configuration:
<http ..... >
...
<intercept-url method="GET" pattern="/groups" access="hasRole('VIEW_GROUPS')" />
<intercept-url method="GET" pattern="/admin" access="hasRole('VIEW_ADMIN')" />
...
<access-denied-handler error-page="/access-denied" />
</http>
URL /access-denied usually displays the access denied page. You could register a controller to that URL and then you could check in the controller if user has role "VIEW_ADMIN" and redirect him there. If you need to know which URL user attempted to visit, it should be available in HttpServletRequest object.
EDIT: solution via interceptor:
You could create a Spring MVC interceptor. Extend HandlerInterceptorAdapter and in the preHandle method check if user is authenticated and check the roles and do a redirect.
class MyRoleBasedRedirectorInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//do the authentication/role/URL checks
...
if (needsAdminRedirect) {
response.sendRedirect("admin");
return false;
}
return true;
}
}
And in the config:
<mvc:interceptors>
<bean class="com.example.MyRoleBasedRedirectorInterceptor" />
</mvc:interceptors>
If you dislike original controller solution you can also implement your own AccessDeniedHandler implementation and to the checks there. You would plug in your implementation with
<access-denied-handler ref="com.example.MyAccessDeniedHandler" />
I would still opt for Controller / AccessDeniedHandler solution since, if I understood correctly, redirect happens only when a user is not authorized to visit "groups" page.
Upvotes: 2