2017-04-25 124 views
0

我正在使用Spring SecurityCAS,並且存在以下問題。當驗證誤差由CAS Server(如無效的用戶名/密碼)拋出它在形式上顯示良好,使用顯示正確標籤:Spring Security CAS:在login.jsp上顯示客戶端錯誤

<form:errors path="*" id="msg" cssClass="alert alert-danger" element="div"/> 

但在情況下,當CAS Server返回成功,AuthenticationException被套上CAS Client無的錯誤顯示爲基本CAS Client重定向回http://localhost:8080/cas/login?service=http%3A%2F%2Flocalhost%3A8080%2Fj_spring_cas_security_check

所以我不能真正顯示客戶端出了什麼問題。是否有可能在相同的JSP上顯示來自客戶端的錯誤,以防萬一出現AuthenticationException

回答

0

不知道如果這是超級乾淨和正確的方式來做到這一點,但我設法做到這一點的方式是使用cookie。

我所要做的只是擴展SimpleUrlAuthenticationFailureHandler,使用request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION) 得到最後一個認證異常並寫入我的自定義錯誤代碼cookie。該代碼是在Scala,但是是非常簡單的:

class CookieAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler{ 

    val clientErrorCookie = "clientError" 

    override def onAuthenticationFailure(request: HttpServletRequest, response: HttpServletResponse, exception: AuthenticationException): Unit = { 
    val authenticationException = SecurityUtility.getSessionAuthException(request).getOrElse(exception) 

    ClientErrors.values 
     .filter(clientError => clientError.exceptionClass.equals(authenticationException.getClass)) 
     .foreach(clientError => response.addCookie(new Cookie(clientErrorCookie, clientError.errorCode))) 

    super.onAuthenticationFailure(request, response, authenticationException) 
    } 
} 

然後,在CAS server邊,我在下面的方式顯示在JSP錯誤:

<c:set var="clientErrorCookie" value="clientError"/> 
<c:if test="${cookie.containsKey(clientErrorCookie)}"> 
        <div class="alert alert-danger"> 
         <spring:message code="error.client.authentication.${cookie.get(clientErrorCookie).value}" 
             text="Client authentication error"/> 
        </div> 
       </c:if> 

和頁面加載後錯誤顯示,我剛剛刪除了該餅乾JS

function deleteCookie(name) { 
      document.cookie = name + '=; Path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; 
     } 

$(document).ready(function(){ 
      deleteCookie('${clientErrorCookie}'); 
     }