0

I have implemented a servlet filter that checks whether the user is logged in and redirects the user to the login page if they are not. The reason I am doing this check as a filter is that the login page exists in an another webapp which I cannot seem to redirect to using web.xml's FROM auth-method to redirect to a page that's in a different webapp with a different context root (note, I am using weblogic 11g).

The problem I am experiencing is that when I have an ajaxified component, like a button, the servlet filter is not able to redirect the user. i.e. they wind up right back on the page that they were on.

Is there a different way I should be doing this logged-in check?

BestPractices
  • 12,738
  • 29
  • 96
  • 140

1 Answers1

2

I re-implemented the servlet filter as a JSF 2.0 Phase Listener that runs before the RESTORE_VIEW phase. By moving the logic into a Phase Listener, I was able to take advantage of JSF's ability to handle redirects for an AJAX request. Basically JSF 2.0 will create the proper AJAX response to cause a redirect on the client side. To be clear, this mechanism is able to do a redirect for AJAX and non-AJAX requests if the user is not logged in.

Specifically, it will send back the following response:

<?xml version="1.0" encoding="utf-8"?>
<partial-response>
  <redirect url="/contextpath/faces/ajax/redirecttarget.xhtml">
  </redirect>
</partial-response>"

Code for the phase listener:

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

public void afterPhase(PhaseEvent event) 
{
    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    HttpSession session = (HttpSession)ec.getSession(false);

    if (session==null || session.getAttribute(IS_LOGGED_IN_INDICATOR) == null) 
    {
        try
        {
            ec.redirect(LOGIN_PAGE_URL);
        }
        catch(IOException e)
        {
            // log exception...
        }           
    }
}
BestPractices
  • 12,738
  • 29
  • 96
  • 140
  • 1
    Note that a PhaseListener doesn't kick in on non-JSF requests. So if you happen to have secured non-JSF resources as well, it won't be checked. You'd need to duplicate the job in the filter, or to do it entirely in the filter. – BalusC May 04 '12 at 21:10