2011-12-24 262 views
0

我用一個小面JSF2的FacesMessage登錄表單爲春季安全:春季安全badcredentials

<h:messages globalOnly="true" layout="table" /> 
<h:form id="formLogin" prependId="false"> 
     <h:outputLabel for="j_username" value="Usuario:" /> 
     <h:inputText id="j_username" value="#{autenticacionController.administrador.login}" /> 
     <h:outputLabel for="j_password" value="Contraseña:" /> 
     <h:inputSecret id="j_password" value="#{autenticacionController.administrador.password}" /> 
     <h:commandButton value="Entrar" action="#{autenticacionController.loginAction}" /> 
     <h:commandButton value="Cancelar" immediate="true" action="#{autenticacionController.cancelarAction}" /> 
</h:form>` 

根據loginAction方法轉發這個請求:

FacesContext.getCurrentInstance().getExternalContext().dispatch("/j_spring_security_check") 

它工作正常,但怎麼也如果Spring Security引發BadCredentials異常,我在h:messages標記中顯示facesmessage?

我知道它可以用階段偵聽器完成,但我不喜歡那種方式(處理偵聽器中的異常)。

我嘗試另一種方式,配置Spring安全性是這樣的:

authentication-failure-url="/faces/paginas/autenticacion/login.xhtml?error=1 

然後在登錄頁面,趕上GET參數「錯誤」。但是我怎樣才能以這種方式顯示臉部信息呢?

我試過的另一種方法是重寫Spring Security的消息屬性文件(覆蓋關鍵字「badcredentials」的消息),但它也沒有工作(我不知道如何顯示消息)。

任何人都知道該怎麼做?

非常感謝您提前。

回答

1

And then in the login page, catch the GET param "error". But how can I show the facesmessage in this way?

這樣:

<f:metadata> 
    <f:viewParam name="error" validator="#{auth.checkErrors}" /> 
</f:metadata> 
<h:messages /> 

public void checkErrors(FacesContext context, UIComponent component, Object value) { 
    if ("1".equals(value)) { 
     throw new ValidatorException(new FacesMessage("Invalid credentials")); 
    } 
} 

也許這樣:

<f:metadata> 
    <f:viewParam name="error" value="#{auth.error}" /> 
    <f:event type="preRenderView" listener="#{auth.checkErrors}" /> 
</f:metadata> 
<h:messages /> 

private int error; 

public void checkErrors() { 
    if (error == 1) { 
     FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Invalid credentials")); 
    } 
} 

無論哪種方式,這感覺很hacky :)

+0

我不認爲這是哈克。我更喜歡它比階段監聽器更好。不過,我寧願從Spfing安全中過濾消息屬性文件,但我不知道該怎麼做。我嘗試過,但沒有奏效。 – choquero70 2011-12-25 16:13:03

+0

隨着hacky我的意思更多,錯誤頁面是書籤和可操作的,可能會導致最終用戶混淆。 – BalusC 2011-12-25 16:14:51

+0

你說得對,謝謝。順便說一下,你知道如何使用Spring Security的消息屬性文件來完成它嗎?我的意思是覆蓋其中的「badCredentials」消息,並顯示facemesage。我看到http://www.mkyong.com/spring-security/display-custom-error-message-in-spring-security/,但我認爲這是在演示級使用Spring,而不是JSF。 – choquero70 2012-01-03 19:33:02