Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AuthenticationSuccessHandler example for Spring Security 3

Tags:

java

spring

I am a newbie to Spring Security 3 . I am using roles for users to login.

I want to redirect a user to a different page based on the role of that user, I understand is that I would have to implement the AuthenticationSuccessHandler for the same, but some examples in that direction would help.

Thanks in advance, Vivek

like image 506
Vivek Avatar asked Sep 19 '11 11:09

Vivek


1 Answers

You can do something like this:

public class Test implements AuthenticationSuccessHandler {
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        if (roles.contains("ROLE_USER") {
            response.sendRedirect("/userpage");
        }
    }
}

In the XML config add this:

<bean id="authenticationFilter" class="YOUR_AUTH_FILTER_HERE">
    <!-- There might be more properties here, depending on your auth filter!! -->
    <property name="authenticationSuccessHandler" ref="successHandler" />
</bean> 

<bean id="successHandler" class="Test"/>
like image 164
nfechner Avatar answered Sep 28 '22 11:09

nfechner