Search code examples
jsfhttp-redirectjsf-2authenticationjaas

Programmatic login via request.login() doesn't redirect to <form-error-page> in case of fail


I'm working in a web app that implement login with Request.login(). The problem is if the login fails the jsf does not redirect to form-error-page. If I use the tradictional method j_security_check everthing works fine. Is there some type of detail to make the same with managed bean login?

ExternalContext externalContext = externalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
request.login(username, password);

In my web.xml

<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>security_domain</realm-name>
    <form-login-config>
        <form-login-page>/pages/login.xhtml</form-login-page>           
        <form-error-page>/pages/loginError.xhtml</form-error-page>
    </form-login-config>
</login-config>

Solution

  • When not directly submitting to /j_security_check URL, the <login-config> is basically entirely ignored, including the <form-error-page>.

    Deal with it yourself:

    try {
        request.login(username, password);
    } catch (ServletException e) {
        externalContext.redirect(externalContext.getRequestContextPath() + "/pages/loginError.xhtml");
    }
    

    Unrelated to the concrete problem, for UX it's actually considered better to stay in the same page with just an error message shown in the form.

    try {
        request.login(username, password);
    } catch (ServletException e) {
        facesContext.addMessage(null, new FacesMessage("Unknown login"));
    }