【发布时间】:2019-09-16 19:56:51
【问题描述】:
我的 Spring Boot(版本 2.2 MI)应用程序只有 REST 端点使用 Spring Security 通过 httpBasic 进行身份验证。但是,当由于未启用用户等原因导致用户身份验证失败时,我想使用自定义 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());
}
【问题讨论】:
标签: spring-boot spring-security basic-authentication