Почему конечная точка /error вызывается перед каждым успешным вызовом API с базовой аутентификацией HTTPJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Почему конечная точка /error вызывается перед каждым успешным вызовом API с базовой аутентификацией HTTP

Сообщение Anonymous »

У меня есть устаревшее приложение Spring Boot 3.2 с Spring Security 6.2, и мне нужно выполнить некоторые обновления. Это служба API без сохранения состояния с базовой аутентификацией HTTP и следующей конфигурацией:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Autowired
UserDetailsServiceImpl userDetailsService;

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(Customizer.withDefaults())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error", "/health").permitAll()
.anyRequest().authenticated())
.requestCache(cache -> cache.disable())
.csrf(csrf -> csrf.disable());

return http.build();
}

Это работает, но я заметил, что при каждом вызове (GET, POST и т. д.) происходит следующее:
  • AuthorizationFilter вызывает /error и получает ошибку 401 (DEBUG org.springframework.web.servlet.DispatcherServlet - выход из диспетчеризации «ОШИБКА», статус 401)
  • Из другого потока вызывает UserDetailsServiceImpl и получает пользователя
  • Начинает регистрацию запроса (DEBUG org.springframework.web.filter.CommonsRequestLoggingFilter — перед запросом [POST...)
  • Правильно запускает вызванную конечную точку и возвращает правильный результат
  • Завершает регистрацию (DEBUG) org.springframework.web.filter.CommonsRequestLoggingFilter — после запроса [POST...)
Проблема не в том, что клиент дважды отправляет запрос (без данных аутентификации и с ними). CommonsRequestLoggingFilter регистрирует только один запрос в каждом тесте.
Это нормально, что вызов /error вызывается при каждом вызове? А если нет, то как это исправить?
Исходный код со всей удаленной бизнес-логикой:
@RestController()
public class EntityController {

@RequestMapping(method = RequestMethod.GET, value = "/entities")
public String getEntities() throws Exception {
return "OK";
}

@RequestMapping(method = RequestMethod.POST, value = "/entities/{id}")
public String postEntity(@PathVariable("id") String id) throws Exception {
return "OK";
}
}

Клиент тестирования:
public class BasicTesting extends AbstractTest {

@Test
public void basicTest() {

given()
.contentType("application/json")
.auth().basic(account, account_pass)
.when()
.get("/entities")
.then()
.statusCode(200);

given()
.contentType("application/xml")
.auth().basic(account, account_pass)
.when()
.post("/entities/myid")
.then()
.statusCode(200);
}
}

Журналы:
14:16:29.516 [http-nio-auto-1-exec-1] INFO org.springframework.web.servlet.DispatcherServlet - Completed initialization in 1 ms
14:16:29.544 [http-nio-auto-1-exec-1] WARN org.springframework.web.servlet.handler.HandlerMappingIntrospector - Cache miss for REQUEST dispatch to '/entities' (previous null). Performing CorsConfiguration lookup. This is logged once only at WARN level, and every time at TRACE.
14:16:29.555 [http-nio-auto-1-exec-1] WARN org.springframework.web.servlet.handler.HandlerMappingIntrospector - Cache miss for REQUEST dispatch to '/entities' (previous null). Performing MatchableHandlerMapping lookup. This is logged once only at WARN level, and every time at TRACE.
14:16:29.605 [http-nio-auto-1-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - "ERROR" dispatch for GET "/error", parameters={}
14:16:29.608 [http-nio-auto-1-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
14:16:29.675 [http-nio-auto-1-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor - Using 'application/json', given [*/*] and supported [application/json, application/*+json]
14:16:29.675 [http-nio-auto-1-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor - Writing [{timestamp=Wed Jan 07 14:16:29 CET 2026, status=401, error=Unauthorized, path=/entities}]
14:16:29.780 [http-nio-auto-1-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Exiting from "ERROR" dispatch, status 401
14:16:29.940 [http-nio-auto-1-exec-3] INFO mypackage.service.UserDetailsServiceImpl - Trying to find for ***********
14:16:30.788 [http-nio-auto-1-exec-3] DEBUG org.springframework.web.filter.CommonsRequestLoggingFilter - Before request [GET /entities, client=127.0.0.1, user=**********]
14:16:30.788 [http-nio-auto-1-exec-3] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/entities", parameters={}
14:16:30.788 [http-nio-auto-1-exec-3] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to mypackage.controller.TestController#getEntities()
14:16:30.788 [http-nio-auto-1-exec-3] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Using 'text/plain', given [*/*] and supported [text/plain, */*, application/json, application/*+json]
14:16:30.788 [http-nio-auto-1-exec-3] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Writing ["OK"]
14:16:30.788 [http-nio-auto-1-exec-3] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 200 OK
14:16:30.788 [http-nio-auto-1-exec-3] DEBUG org.springframework.web.filter.CommonsRequestLoggingFilter - After request [GET /entities, client=127.0.0.1, user=**********]
14:16:31.006 [http-nio-auto-1-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - "ERROR" dispatch for POST "/error", parameters={}
14:16:31.015 [http-nio-auto-1-exec-2] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
14:16:31.015 [http-nio-auto-1-exec-2] DEBUG org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor - Using 'application/json', given [*/*] and supported [application/json, application/*+json]
14:16:31.015 [http-nio-auto-1-exec-2] DEBUG org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor - Writing [{timestamp=Wed Jan 07 14:16:31 CET 2026, status=401, error=Unauthorized, path=/entities/myid}]
14:16:31.025 [http-nio-auto-1-exec-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Exiting from "ERROR" dispatch, status 401
14:16:31.037 [http-nio-auto-1-exec-4] INFO mypackage.service.UserDetailsServiceImpl - Trying to find for **********
14:16:31.149 [http-nio-auto-1-exec-4] DEBUG org.springframework.web.filter.CommonsRequestLoggingFilter - Before request [POST /entities/myid, client=127.0.0.1, user=**********]
14:16:31.149 [http-nio-auto-1-exec-4] DEBUG org.springframework.web.servlet.DispatcherServlet - POST "/entities/myid", parameters={}
14:16:31.149 [http-nio-auto-1-exec-4] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to mypackage.controller.TestController#postEntity(String)
14:16:31.169 [http-nio-auto-1-exec-4] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Using 'text/plain', given [*/*] and supported [text/plain, */*, application/json, application/*+json]
14:16:31.169 [http-nio-auto-1-exec-4] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Writing ["OK"]
14:16:31.171 [http-nio-auto-1-exec-4] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 200 OK
14:16:31.171 [http-nio-auto-1-exec-4] DEBUG org.springframework.web.filter.CommonsRequestLoggingFilter - After request [POST /entities/myid, client=127.0.0.1, user=**********]


Подробнее здесь: https://stackoverflow.com/questions/798 ... asic-authe
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»