3

I have a JSF login page (for Spring Security) and a global message to display a message for wrong login user/pass.

Here is my form:

<f:event listener="#{loginBean.updateMessages}" type="preRenderView"/>

<h:form prependId="false" >

    <h:outputLabel value="User Name:" for="username"/>
    <h:inputText id="username" required="true" value="#{loginBean.name}"/>
    <h:message id="usernMsg" for="username"/> <br/>

    <h:outputLabel value="Password:" for="password"/>
    <h:inputSecret id="password" value="#{loginBean.password}" required="true"/>
    <h:message id="passMsg" for="password"/><br/>

    <h:messages id="glbMsg" globalOnly="true"/><br/>

    <h:commandButton value="Submit" action="#{loginBean.doLogin}"/>

</h:form>

I update messages with updateMessages():

public void updateMessages() {
    Exception ex = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
            .get(WebAttributes.AUTHENTICATION_EXCEPTION);

    if (ex != null) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        setUsername("");
        setPassword("");
    }
}

Problem is when user enter wrong credentials, the message displays, but when user refresh the login page (either with F5 or clicking on submit button while text fields are empty ) , the previous global message (glbMsg) value doesn't removes.

I tried ajax render="..." in submit button and it not worked.

Sajad
  • 2,273
  • 11
  • 49
  • 92

1 Answers1

3

Look back at the problem once again, now in the right way. You actually don't want to clear out the h:messages. You actually want to clear the exception (which triggered the h:messages). It's simply redisplayed every time, because the exception is not null every time.

Spring Security stores the last authentication fail as an exception in the session. The way how you obtained it is evident:

Exception ex = (Exception) FacesContext.getCurrentInstance().getExternalContext()
    .getSessionMap().get(WebAttributes.AUTHENTICATION_EXCEPTION);

Unless you invalidate the session, or Spring Security removes it all by itself, it sticks there around for the entire session. As Spring Security apparently doesn't remove it, you have to do it yourself.

Exception ex = (Exception) FacesContext.getCurrentInstance().getExternalContext()
    .getSessionMap().remove(WebAttributes.AUTHENTICATION_EXCEPTION);
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555