我已经在这里搜索了BasicAuthenticationEntryPoint
的问题,但我不明白我的实际问题。我是一个应用程序,我用基本的身份验证用户/通行证(Authorization: Basic xxxxxxxxxx
头)保护所有端点。但是当身份验证失败时,我需要创建一些自定义异常,因此我创建了自己的入口点类,以便能够合并我的异常。
但是这个入口点只有在**httpBasic()
**从SecurityConfig
中删除时才有效,否则将跳过。
@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);
}
}
我做错了什么?
1条答案
按热度按时间rur96b6h1#
我通过更改配置顺序来解决此问题
通过
有道理