Spring boot Spring引导(2.2 MI)安全性:为HttpBasic配置自定义身份验证FailureHandler
我的Spring Boot(版本2.2 MI)应用程序只有使用Spring安全性通过httpBasic验证的REST端点。但是,当由于用户未启用等原因导致用户身份验证失败时,我希望使用自定义Json进行响应,以便我的React本机应用程序适当地指导用户。但是,自定义AuthenticationFailureHandler似乎只能为formLogin配置 我只看到这样的例子Spring boot Spring引导(2.2 MI)安全性:为HttpBasic配置自定义身份验证FailureHandler,spring-boot,spring-security,basic-authentication,Spring Boot,Spring Security,Basic Authentication,我的Spring Boot(版本2.2 MI)应用程序只有使用Spring安全性通过httpBasic验证的REST端点。但是,当由于用户未启用等原因导致用户身份验证失败时,我希望使用自定义Json进行响应,以便我的React本机应用程序适当地指导用户。但是,自定义AuthenticationFailureHandler似乎只能为formLogin配置 我只看到这样的例子 http. formLogin(). failureHandler(customAuthenticati
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();
}
但是,我需要下面这样的东西(这是不存在的)
请让我知道,前进的最佳方式是什么
更新:-
根据下面接受的答案,下面是自定义实现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
。默认的代码是@Bean
public AuthenticationEntryPoint customBasicAuthenticationEntryPoint() {
return new CustomBasicAuthenticationEntryPoint();
}
并通过以下方式进行配置:
http.httpBasic().authenticationEntryPoint(customBasicAuthenticationEntryPoint())
http.httpBasic().authenticationEntryPoint(customBasicAuthenticationEntryPoint())