Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine target url based on roles in spring security 3.1

In spring security 3.0, we are having AuthenticationProcessingFilter class, in which we were using determineTargetUrl() method, which returned the url based on different roles.

Now, we are moving to spring security 3.1.0.RC3 and I am stuck how should I now determine the url based on different roles as AuthenticationProcessingFilter class has been removed from new version. Can anyone please give me steps in brief with some code so that I can implement custom filter to redirect to different pages for different roles.

like image 590
Mital Pritmani Avatar asked Nov 30 '11 13:11

Mital Pritmani


1 Answers

The best way to determine the target url based upon roles is to specify a target url in your Spring Security configuration as shown below. This will work in Spring 3.0 or 3.1

<http>
    ... 
    <form-login login-page="/login" default-target-url="/default"/>
</http>

Then create a controller that processes the default-target-url. The controller should redirect or forward based upon rolls. Below is an example of using Spring MVC, but any type of controller will work (i.e. Struts, a Servlet, etc).

@Controller
public class DefaultController {
    @RequestMapping("/default")
    public String defaultAfterLogin(HttpServletRequest request) {
        if (request.isUserInRole("ROLE_ADMIN")) {
            return "redirect:/users/sessions";
        }
        return "redirect:/messages/inbox";
    }
}

The advantages to this approach are it is not coupled to any specific implementation of Security, it is not coupled to any specific MVC implementation, and it works easily with Spring Security namespace configuration. A full example can be found in the SecureMail project I presented at SpringOne this year.

An alternative is that you could create a custom AuthenticationSuccessHandler. The implementation might extend SavedRequestAwareAuthenticationSuccessHandler which is the default AuthenticationSuccessHandler. it could then be wired using the namespace as shown below.

<sec:http>
    <sec:form-login authentication-success-handler-ref="authSuccessHandler"/>
</sec:http>
<bean:bean class="example.MyCustomAuthenticationSuccessHandler"/>

I would not recommend doing this as it is tied to Spring Security API's and it is better to avoid that when possible.

like image 127
Rob Winch Avatar answered Oct 14 '22 20:10

Rob Winch