How to use j_security_check jsf

angus picture angus · Feb 1, 2014 · Viewed 7.7k times · Source

I want to use j_security_check authentication in order to validate the user credentials.

Basically what I am trying to achieve is when the user press submit then in case he is using wrong credentials then a message (p:growl) will show and if it’s successful then the dialog will closed.

There are many examples in the web but unfortunately I still can’t understand how to complete this puzzle :(

In my project I am using primefaces 4.0 & weblogic 10.3.2.0 (JAVA EE 5).

some code example:

<p:dialog id="dialog" widgetVar="dlg" resizable="false"> 
    <h:form id="fLogin" prependId="false"
            onsubmit="document.getElementById('fLogin').action = 'j_security_check';">        
        <h:panelGrid columns="2" cellpadding="5">  
            <h:outputLabel for="j_username" value="Username:" />  
            <p:inputText value="#{expBean.username}"   
                         id="j_username" label="username"/>  
            <h:outputLabel for="j_password" value="Password:" />  
            <h:inputSecret value="#{expBean.password}"   
                           id="j_password" label="password"/>  
            <p:commandButton id="submitButton" 
                             value="Submit"
                             actionListener="#{expBean.run}" /> 
        </h:panelGrid> 
    </h:form>
</p:dialog>

web.xml

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
    <url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<security-constraint>
    <web-resource-collection>
        <web-resource-name>main</web-resource-name>
        <description/>
        <url-pattern>main.jsf</url-pattern>
        <http-method>POST</http-method>
    </web-resource-collection>
</security-constraint>
<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>my-realm</realm-name>
</login-config>
<security-role>
    <description/>
    <role-name>MyRole</role-name>
</security-role>

exeBean:

   public void run() {


      FacesContext facesContext = FacesContext.getCurrentInstance();

   }

Any guidelines and useful example will be much appreciated

Thanks

Answer

BalusC picture BalusC · Feb 3, 2014

You were submitting the form by PrimeFaces ajax. That's why it fails. The j_security_check handler doesn't understand incoming JSF/PrimeFaces-flavored ajax requests and can't handle them appropriately by returning the desired XML response. It has to be a regular (synchronous) submit.

Turn off the ajax thing:

<p:commandButton ... ajax="false" />

By the way, your form declaration is clumsy. Just use <form> instead of <h:form>.

<form id="fLogin" action="j_security_check">