Spring boot(2.2 MI) 安全:为 HttpBasic 配置自定义 AuthenticationFailureHandler

Spring boot(2.2 MI) Security : Configure custom AuthenticationFailureHandler for HttpBasic

我的 Spring Boot(MI 版本 2.2)应用程序仅使用 spring 安全性通过 httpBasic 验证 REST 端点。但是,当由于用户未启用等原因导致用户身份验证失败时,我想使用自定义 Json 进行响应,以便我的 React Native 应用程序适当地引导用户。但是,自定义 AuthenticationFailureHandler 似乎只能为 formLogin 配置。

我只看到例子

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();
}

但是,我需要像下面这样的东西(似乎没有)

http.
   httpBasic().
       failureHandler(customAuthenticationFailureHandler());

请告诉我,前进的最佳方式是什么?

更新:- 根据下面接受的答案,下面是自定义实现 CustomBasicAuthenticationEntryPoint

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());
}

BasicAuthenticationFilter认证失败时,会调用AuthenticationEntryPoint。默认的是BasicAuthenticationEntryPoint,你可以考虑写一个自定义的或者扩展它:

@Bean
public AuthenticationEntryPoint customBasicAuthenticationEntryPoint() {
    return new CustomBasicAuthenticationEntryPoint();
}

并通过以下方式配置它:

   http.httpBasic().authenticationEntryPoint(customBasicAuthenticationEntryPoint())