سؤال

I have a PhaseListener to control the user access to some pages, if the user is not logged he is redirected to loginpage.

The problem is that my method handleNavigation is not redirecting the user. It runs but does not redirect the user.

When the user types a url that should not have access, the method runs but he page opens without redirected to the login page.

What is wrong?

public class AuthorizationListener implements PhaseListener {

  public void afterPhase(PhaseEvent event) {

    FacesContext facesContext = event.getFacesContext();
    String currentPage = facesContext.getViewRoot().getViewId();

    boolean isLoginPage = (currentPage.lastIndexOf("login.xhtml") > -1);
    if(isLoginPage)
      return;

    if(currentPage.indexOf("/rws/") != -1)
    {
      HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
      Object currentUser = session.getAttribute("usuario");

      if (!isLoginPage && currentUser == null) {
        NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
        nh.handleNavigation(facesContext, null, "loginPage");
      }
  } 
}

public void beforePhase(PhaseEvent event) {
    System.out.println("Hellow World");
}

public PhaseId getPhaseId() {
  return PhaseId.RENDER_RESPONSE;
}

}

My faces-config

<navigation-rule>
  <from-view-id>/*</from-view-id>
  <navigation-case>
    <from-outcome>loginPage</from-outcome>
    <to-view-id>/login.xhtml</to-view-id>
  </navigation-case>
</navigation-rule>

<lifecycle>
  <phase-listener>br.com.testes.filter.AuthorizationListener</phase-listener>
</lifecycle>
هل كانت مفيدة؟

المحلول

You're executing the code during after phase of render response. That's thus after JSF has rendered and completed the response. At that moment, the whole HTTP response is already finished and completely sent to the webbrowser.

This is a point of no return. Your code is simply being too late in order to change the response.

Listen on restore view phase instead. Or, better, use a servlet filter. A JSF phase listener is an overly clumsy tool for the job (it does not kick in on non-JSF requests and is triggered up to 12 times during a JSF request). A servlet filter is the right tool for the job. You can find a concrete example in this answer: JSF page style missing when using login filter.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top