我的Spring Boot(2.2 MI版)应用程序仅具有使用Spring Security通过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());
}
答案 0 :(得分:1)
BasicAuthenticationFilter
认证失败时,它将调用AuthenticationEntryPoint
。默认值是BasicAuthenticationEntryPoint
,您可以考虑编写自定义值或扩展自定义值:
@Bean
public AuthenticationEntryPoint customBasicAuthenticationEntryPoint() {
return new CustomBasicAuthenticationEntryPoint();
}
并通过以下方式进行配置:
http.httpBasic().authenticationEntryPoint(customBasicAuthenticationEntryPoint())