我已经在这里搜索 BasicAuthenticationEntryPoint 的问题,但我不明白我的实际问题。我是一个应用程序,我正在使用基本身份验证用户/密码(授权:基本 xxxxxxxxxx 标头)保护所有端点。但是我需要在身份验证失败时创建一些自定义异常,所以我创建了自己的入口点类以便能够合并我的异常。
但是这个入口点只有在从 SecurityConfig 中删除 httpBasic() 时才有效,否则将被跳过。
@Configuration
@EnableWebSecurity
public class SecurityConfig{
....
http.authorizeHttpRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.exceptionHandling()
.authenticationEntryPoint(customBasicAuthEntryPoint);
return http.build();
}
@Component
public class CustomBasicAuthEntryPoint extends BasicAuthenticationEntryPoint {
private final ObjectMapper objectMapper;
public CustomBasicAuthEntryPoint(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
Error error = new Error();
if (authException instanceof BadCredentialsException){
error.setMessage("Unauthorized please add a basic auth");
error.setStatusCode(HttpStatus.UNAUTHORIZED.value());
error.setTimestamp(Timestamp.from(Instant.now()));
}
else{
error.setMessage(authException.getMessage());
error.setStatusCode(response.getStatus());
error.setTimestamp(Timestamp.from(Instant.now()));
}
response.setStatus(error.getStatusCode());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
objectMapper.writeValue(response.getWriter(), error);
}
}
我做错了什么?谢谢
我通过更改配置顺序解决了这个问题
http.authorizeHttpRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.exceptionHandling()
.authenticationEntryPoint(customBasicAuthEntryPoint);
by
http.authorizeHttpRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(customBasicAuthEntryPoint)
.and();
有道理
谢谢