title: Spring boot(2.2 MI) Security : Configure custom AuthenticationFailureHandler for HttpBasic
body: <p>My Spring Boot ( Version 2.2 MI) application is having only REST endpoints authenticated with httpBasic using spring security. But, when the user authentication fails due to user not being enabled etc, I would like to respond with the custom Json so that my React Native app guide the user appropriately. But, custom AuthenticationFailureHandler seems to be configurable only for formLogin.</p>
  
  <p>I see examples only like</p>
  
  <pre><code>http.
     formLogin().
         failureHandler(customAuthenticationFailureHandler());
  
  public class CustomAuthenticationFailureHandler
     implements AuthenticationFailureHandler {
         @Override
         public void onAuthenticationFailure(
             HttpServletRequest request,
             HttpServletResponse response,
             AuthenticationException exception)
             throws IOException, ServletException {
         }
  }
  @Bean
  public AuthenticationFailureHandler customAuthenticationFailureHandler() {
      return new CustomAuthenticationFailureHandler();
  }
  </code></pre>
  
  <p>But, I need something like below (which is not seesm to be there)</p>
  
  <pre><code>http.
     httpBasic().
         failureHandler(customAuthenticationFailureHandler());
  </code></pre>
  
  <p>Please let me know, whats the best way to go forward ?</p>
  
  <p>Update :-
  As per the accepted answer below, below is the custom implementation CustomBasicAuthenticationEntryPoint </p>
  
  <pre><code>import javax.servlet.ServletException;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.IOException;
  
  public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
      @Override
      public void commence(HttpServletRequest request, HttpServletResponse response,
                           AuthenticationException authException) throws IOException, ServletException {
          response.addHeader("WWW-Authenticate", "Basic realm=\"" + this.getRealmName() + "\"");
          //response.sendError( HttpStatus.UNAUTHORIZED.value(), "Test msg response");
          response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
          response.setContentType("application/json");
          response.setCharacterEncoding("UTF-8");
          response.getWriter().write("{ \"val\":\"Venkatesh\"}");
      }
  }
  
  @Bean
      public AuthenticationEntryPoint customBasicAuthenticationEntryPoint() {
          CustomBasicAuthenticationEntryPoint obj = new CustomBasicAuthenticationEntryPoint();
          obj.setRealmName("YourAppName");
          return obj;
      }
  
  protected void configure(HttpSecurity http) throws Exception{
          http.httpBasic().
                  authenticationEntryPoint(customBasicAuthenticationEntryPoint());
  }
  </code></pre>