Spring Security 页面刷新后清除h:消息

6kkfgxo0  于 2022-11-24  发布在  Spring
关注(0)|答案(1)|浏览(172)

我有一个JSF登录页面(用于Spring Security)和一个全局消息,显示错误登录用户/密码的消息。
下面是我的表单:

  1. <f:event listener="#{loginBean.updateMessages}" type="preRenderView"/>
  2. <h:form prependId="false" >
  3. <h:outputLabel value="User Name:" for="username"/>
  4. <h:inputText id="username" required="true" value="#{loginBean.name}"/>
  5. <h:message id="usernMsg" for="username"/> <br/>
  6. <h:outputLabel value="Password:" for="password"/>
  7. <h:inputSecret id="password" value="#{loginBean.password}" required="true"/>
  8. <h:message id="passMsg" for="password"/><br/>
  9. <h:messages id="glbMsg" globalOnly="true"/><br/>
  10. <h:commandButton value="Submit" action="#{loginBean.doLogin}"/>
  11. </h:form>

我使用updateMessages()更新消息:

  1. public void updateMessages() {
  2. Exception ex = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
  3. .get(WebAttributes.AUTHENTICATION_EXCEPTION);
  4. if (ex != null) {
  5. FacesContext.getCurrentInstance().addMessage(null,
  6. new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
  7. setUsername("");
  8. setPassword("");
  9. }
  10. }

问题是,当用户输入错误凭据时,消息显示,但当用户刷新登录页面(使用F5或在文本字段为空时单击提交按钮)时,之前的全局消息(glbMsg)值不会删除。
我在提交按钮中尝试了ajax render="...",但没有成功。

xurqigkl

xurqigkl1#

现在,我们用正确的方式再次回顾一下这个问题。实际上,您并不想清除h:messages。您实际上想清除异常(它触发了h:messages)。它只是每次都重新显示,因为异常并不是每次都是null
Spring Security将上次的身份验证失败作为异常存储在session中。获取它的方式很明显:

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

除非您使会话无效,或者Spring Security自己删除它,否则它会在整个会话中一直存在。

  1. Exception ex = (Exception) FacesContext.getCurrentInstance().getExternalContext()
  2. .getSessionMap().remove(WebAttributes.AUTHENTICATION_EXCEPTION);

相关问题