Spring security authenticate exceptions handling

前端 未结 3 684
星月不相逢
星月不相逢 2020-12-09 19:18

I have an app using Spring Security 3.0.x. There I have a custom AuthenticationProvider:

public class A         


        
相关标签:
3条回答
  • 2020-12-09 19:19

    Use the below tags for your customize authentication in jsp page.

    <c:if test="${sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message eq 'Bad credentials'}">
    Username/Password entered is incorrect.
    </c:if>
    <c:if test="${sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message eq 'User is disabled'}">
    Your account is disabled, please contact administrator.
    </c:if>
    <c:if test="${fn:containsIgnoreCase(sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message,'A communications error has been detected')}">
    Database connection is down, try after sometime.
    </c:if>
    

    Also include the below tag library for properly working

    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec"%>
    

    ...

    0 讨论(0)
  • 2020-12-09 19:23

    It's usually a bad idea to provide details on why an authentication failed as it can provide an attacker with useful information. For example, it can allow them to probe for valid account names.

    If you need to customize things, then rather than using an authentication-failure-url, you can use authentication-failure-handler-ref to inject a custom AuthenticationFailureHandler bean where you can implement different behaviour depending on the exception.

    0 讨论(0)
  • 2020-12-09 19:43

    Authentication failure handler :

    public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
      super.onAuthenticationFailure(request, response, exception);
      if(exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) {
        showMessage("BAD_CREDENTIAL");
      } else if (exception.getClass().isAssignableFrom(DisabledException.class)) {
        showMessage("USER_DISABLED");
      }
    }
    

    configuration :

    <bean id="customAuthenticationFailureHandler"
          class="com.apackage.CustomAuthenticationFailureHandler">
        <property name="defaultFailureUrl" value="/index.jsp"/>
    </bean>
    <security:http auto-config="true">
      <security:form-login default-target-url="/welcome.jsp" authentication-failure-handler-ref="customAuthenticationFailureHandler" />
    </security:http>
    
    0 讨论(0)
提交回复
热议问题