Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...