不知道如果這是超級乾淨和正確的方式來做到這一點,但我設法做到這一點的方式是使用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}');
}