Приложение My Spring Boot (версия 2.2 MI) имеет только конечные точки REST, аутентифицированные с помощью httpBasic с использованием Spring Security. Но когда аутентификация пользователя завершается неудачно из-за того, что пользователь не включен и т. Д., Я хотел бы ответить пользовательским 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());
}