Search code examples
authenticationexceptionspring-security

Spring security authenticate exceptions handling


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

public class AppAuthenticationProvider implements AuthenticationProvider {
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        ...
        if (!check1()) throw new UsernameNotFoundException();
        if (!check2()) throw new DisabledException();
        ...
    }

I'd like to send custom response codes on each exception, for example 404 for UsernameNotFoundException, 403 for DisabledException etc. For now, I just have authentication-failure-url in my spring security configuration so I get redirect to it on each exception in authenticate().


Solution

  • 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>