Spring Security CAS:在login.jsp上显示客户端错误

时间:2017-04-25 14:22:14

标签: spring jsp spring-security cas spring-security-cas

我正在Spring Security使用CAS并遇到以下问题。当从CAS Server抛出身份验证错误(例如,无效的用户名/密码)时,它会在表单中显示正确并使用标记正确显示:

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

但是,如果CAS Server返回成功且AuthenticationExceptionCAS Client投放,则不会显示任何错误,因为基本上CAS Client重定向回http://localhost:8080/cas/login?service=http%3A%2F%2Flocalhost%3A8080%2Fj_spring_cas_security_check

所以我无法真正显示客户端出了什么问题。是否有可能在同一个JSP上显示来自客户端的错误,以防它抛出AuthenticationException

1 个答案:

答案 0 :(得分: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中删除了该Cookie:

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

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