我的Spring Boot(版本2.2 MI)应用程序只使用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())