Search code examples
jsf-2primefacesspring-securityjava-ee-6

Spring Security:redirection to a specific page based on roles in JSF


I work with JSF and Spring Security. I use a custom login page. I have two roles : Administrator and User. My question is how to redirect to different pages for different roles. For example if the user is an administrator, he will be redirected to "dashboard_Admin.jsf" and if he is a simple user, he will be redirected to "dashboard_user.jsf".

This is my spring security file :

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/security 
                http://www.springframework.org/schema/security/spring-security-3.1.xsd">



<security:http auto-config="true" use-expressions="true">
    <security:intercept-url pattern="/pages/**"
        access="hasRole('ROLE_ADMIN')" />
    <security:form-login login-page="/login.jsf"
        authentication-failure-url="/login.jsf?error=true"
        default-target-url="/pages/admin/dashboard_Admin.jsf" />
    <security:logout logout-success-url="/login.jsf"
        delete-cookies="JSESSIONID" invalidate-session="true" />
    <security:session-management
        invalid-session-url="/login.jsf">
        <security:concurrency-control
            max-sessions="1" error-if-maximum-exceeded="true" />
    </security:session-management>
</security:http>


<security:authentication-manager alias="authenticationManager">
    <security:authentication-provider>
        <security:user-service>
            <security:user name="test" password="test"
                authorities="ROLE_USER" />
            <security:user name="sam" password="sam" authorities="ROLE_ADMIN" />
        </security:user-service>
    </security:authentication-provider>
</security:authentication-manager>

This is my doLogin method:

 public String doLogin() throws ServletException, IOException {

    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();

    RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
            .getRequestDispatcher("/j_spring_security_check?j_username=" + username
                            + "&j_password=" + password);

    dispatcher.forward((ServletRequest) context.getRequest(),
            (ServletResponse) context.getResponse());

    FacesContext.getCurrentInstance().responseComplete();

    return null;
}

Solution

  • I find a very easy solution without using Spring Security, and it works very good. Thanks Ravi