API Spring Boot выдает 403 после множества успешных 200 ответовJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 API Spring Boot выдает 403 после множества успешных 200 ответов

Сообщение Anonymous »


У меня есть приложение Spring Boot, которое использует Spring Security в качестве зависимости. Я переношу загрузочную версию Spring с 2.7.16 на 3.2.1. В версии 2.7.16 все работает нормально. Но в 3.2.1 остальные API через некоторое время выдают 403. Иногда через 5 минут, иногда через час. Итак, вначале он дает 200 успешных ответов, а через некоторое время выдает 403. Я не смог решить проблему после многих попыток. Делюсь конфигурациями безопасности. Любая помощь приветствуется

2.7.16 конфигурация безопасности;

import lombok.RequiredArgsConstructor; импортировать org.springframework.context.annotation.Bean; импортировать org.springframework.context.annotation.Configuration; импортировать org.springframework.http.HttpMethod; импортировать org.springframework.security.authentication.AuthenticationManager; импортировать org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; импортировать org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; импортировать org.springframework.security.config.annotation.web.builders.HttpSecurity; импортировать org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; импортировать org.springframework.security.config.http.SessionCreationPolicy; импортировать org.springframework.security.web.SecurityFilterChain; импортировать org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider; импортировать org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesUserDetailsService; импортировать org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter; @Конфигурация @EnableWebSecurity @EnableGlobalMethodSecurity (prePostEnabled = true) @RequiredArgsConstructor общественный класс SecurityConfiguration { частная окончательная конфигурация AuthenticationConfiguration; @Бин protected SecurityFilterChain filterChain(HttpSecurity http) выдает исключение { http .authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() .antMatchers("/h2-console/**").permitAll() .antMatchers("/manage/info").permitAll() .antMatchers("/manage/health").permitAll() .anyRequest().аутентифицированный() .и() .addFilter(authenticationFilter()) .csrf().отключить() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .и() .httpBasic() .и() .headers().frameOptions().disable(); вернуть http.build(); } @Бин public AuthenticationManager AuthenticationManager() выдает исключение { вернуть конфигурацию.getAuthenticationManager(); } @Бин public RequestHeaderAuthenticationFilter authenticationFilter() выдает исключение { Фильтр RequestHeaderAuthenticationFilter = новый RequestHeaderAuthenticationFilter (); filter.setPrincipalRequestHeader(HeaderConstants.PRINCIPAL_HEADER); filter.setExceptionIfHeaderMissing(false); filter.setAuthenticationManager(authenticationManager()); filter.setAuthenticationDetailsSource(новый HeaderAuthenticationDetailsSource()); обратный фильтр; } @Бин public PreAuthenticatedAuthenticationProvider аутентификацияПровидер () { Поставщик PreAuthenticatedAuthenticationProvider = новый PreAuthenticatedAuthenticationProvider (); поставщик.setPreAuthenticatedUserDetailsService(новый PreAuthenticatedGrantedAuthoritiesUserDetailsService()); поставщик возврата; } } А вот конфигурация безопасности 3.2.1;

import lombok.RequiredArgsConstructor; импортировать org.springframework.context.annotation.Bean; импортировать org.springframework.context.annotation.Configuration; импортировать org.springframework.security.authentication.AuthenticationManager; импортировать org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; импортировать org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; импортировать org.springframework.security.config.annotation.web.builders.HttpSecurity; импортировать org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; импортировать org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; импортировать org.springframework.security.config.annotation.web.configurers.HeadersConfigurer; импортировать org.springframework.security.config.http.SessionCreationPolicy; импортировать org.springframework.security.web.SecurityFilterChain; импортировать org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider; импортировать org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesUserDetailsService; импортировать org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter; импортировать статический org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; @Конфигурация @EnableWebSecurity @EnableMethodSecurity @RequiredArgsConstructor общественный класс SecurityConfiguration { частная окончательная конфигурация AuthenticationConfiguration; @Бин public SecurityFilterChain filterChain(HttpSecurity http) выдает исключение { http .csrf(AbstractHttpConfigurer::отключить) .authorizeHttpRequests(аутентификация -> аутентификация .requestMatchers(antMatcher("/h2-console/**")).permitAll() .requestMatchers(antMatcher("/manage/info")).permitAll() .requestMatchers(antMatcher("/manage/health")).permitAll() .anyRequest().аутентифицированный() ) .addFilter(authenticationFilter()) .headers(заголовки -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) ; вернуть http.build(); } @Бин public AuthenticationManager AuthenticationManager() выдает исключение { вернуть конфигурацию.getAuthenticationManager(); } @Бин public RequestHeaderAuthenticationFilter authenticationFilter() выдает исключение { Фильтр RequestHeaderAuthenticationFilter = новый RequestHeaderAuthenticationFilter (); filter.setPrincipalRequestHeader(HeaderConstants.PRINCIPAL_HEADER); filter.setExceptionIfHeaderMissing(false); filter.setAuthenticationManager(authenticationManager()); filter.setAuthenticationDetailsSource(новый HeaderAuthenticationDetailsSource()); обратный фильтр; } @Бин public PreAuthenticatedAuthenticationProvider аутентификацияПровидер () { Поставщик PreAuthenticatedAuthenticationProvider = новый PreAuthenticatedAuthenticationProvider (); поставщик.setPreAuthenticatedUserDetailsService(новый PreAuthenticatedGrantedAuthoritiesUserDetailsService()); поставщик возврата; } } Журналы приложений: (при выдаче 403 ошибок печати нет)

> :: Spring Boot :: (v3.2.1) 2024-01-05T13:46:10.700Z > ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [основной] > c.p.p.w.time.xxxxTimeApplication : Запуск xxxxTimeApplication > использование Java 17.0.6 с PID 1 > (/home/appuser/yyyy-xxxx-time-3.0.0-SNAPSHOT.jar, запущенный пользователем приложения в > /) 2024-01-05T13:46:10.806Z ОТЛАДКА 1 --- [гггг-хххх-время] [ > main] c.p.p.w.time.xxxxTimeApplication: запуск с помощью Spring Boot > v3.2.1, Spring v6.1.2 2024-01-05T13:46:10.808Z ИНФОРМАЦИЯ 1 --- > [гггг-хххх-время] [основное] c.p.p.w.time.xxxxTimeApplication > : Активен следующий 1 профиль: "test" 2024-01-05T13:46:11.813Z > ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [основной] > o.s.c.c.c.ConfigServerConfigDataLoader: получение конфигурации с сервера. > в: > http://internal-579-yyyy-Internal-ALB-T ... 888/config > 2024-01-05T13:46:11.814Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] o.s.c.c.c.ConfigServerConfigDataLoader: Расположенная среда: > name=yyyy-xxxx-time, Profiles=[default], label=null, > версия = 21809b832fd25e40058d6ab63d42fdfc50c0c2fd, состояние = ноль > 2024-01-05T13:46:11.897Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] o.s.c.c.c.ConfigServerConfigDataLoader: получение конфигурации из >сервер по адресу: > http://internal-579-yyyy-Internal-ALB-T ... 888/config > 2024-01-05T13:46:11.897Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] o.s.c.c.c.ConfigServerConfigDataLoader: Расположенная среда: > name=yyyy-xxxx-time, Profiles=[test], label=null, > версия = 21809b832fd25e40058d6ab63d42fdfc50c0c2fd, состояние = ноль > 2024-01-05T13:46:31.303Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] .s.d.r.c.RepositoryConfigurationDelegate: загрузка Spring > Репозитории данных JPA в режиме DEFAULT. 2024-01-05T13:46:32.399Z ИНФОРМАЦИЯ > 1 --- [гггг-хххх-время] [основной] > .s.s.d.r.c.RepositoryConfigurationDelegate: готовые данные Spring > сканирование репозитория за 997 мс. Найдено 4 интерфейса репозитория JPA. > 2024-01-05T13:46:37.003Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] o.s.cloud.context.scope.GenericScope: BeanFactory > id=2481d7e8-3de7-3e35-9b02-d46f66444038 2024-01-05T13:46:49.008Z ИНФОРМАЦИЯ > 1 --- [гггг-хххх-время] [основной] > o.s.b.w.embedded.tomcat.TomcatWebServer: Tomcat инициализируется с помощью > порт 9061 (http) 2024-01-05T13:46:49.219Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] > [ main] o.apache.catalina.core.StandardService : Запуск > сервис [Tomcat] 2024-01-05T13:46:49.296Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] > [ main] o.apache.catalina.core.StandardEngine : Запуск > Механизм сервлетов: [Apache Tomcat/10.1.17] 2024-01-05T13:46:49.807Z ИНФОРМАЦИЯ > 1 --- [гггг-хххх-время] [основной] > o.a.c.c.C.[Tomcat].[localhost].[/] : Инициализация Spring > встроенный WebApplicationContext 2024-01-05T13:46:49.897Z ИНФОРМАЦИЯ 1 --- > [гггг-хххх-время] [основное] > w.s.c.ServletWebServerApplicationContext: Корневой контекст веб-приложения: > инициализация завершена за 37901 мс 2024-01-05T13:46:57.104Z ИНФОРМАЦИЯ 1 > --- [yyyy-xxxx-time] [main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 — Начало... > 2024-01-05T13:47:01.998Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] com.zaxxer.hikari.pool.HikariPool: HikariPool-1 — добавлено > соединение org.postgresql.jdbc.PgConnection@1071ae7c > 2024-01-05T13:47:02.002Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] com.zaxxer.hikari.HikariDataSource: HikariPool-1 — Старт > завершено. 2024-01-05T13:47:03.396Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] o.hibernate.jpa.internal.util.LogHelper: HHH000204: Обработка > PersistenceUnitInfo [имя: по умолчанию] 2024-01-05T13:47:05.498Z ИНФОРМАЦИЯ 1 > --- [yyyy-xxxx-time] [main] org.hibernate.Version: HHH000412: Базовая версия Hibernate ORM 6.4.1.Final > 2024-01-05T13:47:06.702Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] o.h.c.internal.RegionFactoryInitiator: HHH000026: > Кэш второго уровня отключен 2024-01-05T13:47:10.608Z INFO 1 --- > [гггг-хххх-время] [основной] o.s.o.j.p.SpringPersistenceUnitInfo > : Нет настройки LoadTimeWeaver: игнорируется преобразователь классов JPA. > 2024-01-05T13:47:11.408Z ПРЕДУПРЕЖДЕНИЕ 1 --- [гггг-хххх-время] [ > main] org.hibernate.orm.deprecation: HHH90000025: > PostgreSQLDialect не нужно указывать явно с помощью > «hibernate.dialect» (удалите настройку свойства, и она будет > выбрано по умолчанию) 2024-01-05T13:47:28.707Z ИНФОРМАЦИЯ 1 --- > [гггг-хххх-время] [основной] o.h.e.t.j.p.i.JtaPlatformInitiator > : HHH000489: Платформа JTA недоступна (установите > «hibernate.transaction.jta.platform», чтобы включить платформу JTA > интеграция) 2024-01-05T13:47:28.796Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] j.LocalContainerEntityManagerFactoryBean: инициализированный JPA > EntityManagerFactory для единицы персистентности «по умолчанию» > 2024-01-05T13:47:34.404Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] o.s.d.j.r.query.QueryEnhancerFactory: режим гибернации включен. > путь к классам; Если применимо, будет использоваться парсер HQL. > 2024-01-05T13:47:46.001Z ПРЕДУПРЕЖДЕНИЕ 1 --- [гггг-хххх-время] [ > main] JpaBaseConfiguration$JpaWebConfiguration: > Spring.jpa.open-in-view включен по умолчанию. Следовательно, база данных > запросы могут выполняться во время рендеринга представления. Явно настроить > Spring.jpa.open-in-view, чтобы отключить это предупреждение > 2024-01-05T13:48:01.505Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] o.s.b.a.e.web.EndpointLinksResolver: раскрытие 1 > конечные точки под базовым путем «/manage» 2024-01-05T13:48:03.204Z ИНФОРМАЦИЯ > 1 --- [гггг-хххх-время] [основной] > o.s.s.web.DefaultSecurityFilterChain: защитит любой запрос. > с > [org.springframework.security.web.session.DisableEncodeUrlFilter@3514d1a4, > org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@1177049c, > org.springframework.security.web.context.SecurityContextHolderFilter@5fcaaf92, > org.springframework.security.web.header.HeaderWriterFilter@4a9463b2, > org.springframework.web.filter.CorsFilter@2c05303d, > org.springframework.security.web.authentication.logout.LogoutFilter@15329cf9, > org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter@338a4c61, > org.springframework.security.web.savedrequest.RequestCacheAwareFilter@6685d5e4, > org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2004e611, > org.springframework.security.web.authentication.AnonymousAuthenticationFilter@32394a4b, > org.springframework.security.web.access.ExceptionTranslationFilter@69f564ab, > org.springframework.security.web.access.intercept.AuthorizationFilter@6deda1cd] > 2024-01-05T13:48:15.607Z ИНФОРМАЦИЯ 1 --- [гггг-хххх-время] [ > main] o.s.b.w.embedded.tomcat.TomcatWebServer: Tomcat запущен > порт 9061 (http) с контекстным путем '' 2024-01-05T13:48:15.915Z ИНФОРМАЦИЯ 1 > --- [yyyy-xxxx-time] [main] c.p.p.w.time.xxxxTimeApplication : Запущено xxxxTimeApplication в > 145,407 секунд (процесс выполняется 155,987 секунд) Проверка работоспособности регистрируется в Jenkins при возникновении ошибки:
Успех: код состояния 200 находится в допустимом диапазоне: 200. ОШИБКА: этап сборки не выполнен с исключением hudson.AbortException: Fail: ответ не содержит ожидаемого контента «_links» при вызове https://demo.xxxx.yyyy.com/zzzz/api в jenkins.plugins.http_request.HttpRequestExecution.processResponse(HttpRequestExecution.java:485) в jenkins.plugins.http_request.HttpRequestExecution.authAndRequest(HttpRequestExecution.java:376) в jenkins.plugins.http_request.HttpRequestExecution.call(HttpRequestExecution.java:284) Вызвано: java.lang.IllegalStateException. в jenkins.plugins.http_request.HttpRequestExecution.call(HttpRequestExecution.java:287) в jenkins.plugins.http_request.HttpRequestExecution.call(HttpRequestExecution.java:80) в hudson.remoting.LocalChannel.call(LocalChannel.java:47) в jenkins.plugins.http_request.HttpRequest.perform(HttpRequest.java:449) в hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20) в hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:818) в hudson.model.Build$BuildExecution.build(Build.java:199) в hudson.model.Build$BuildExecution.doRun(Build.java:164) в hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:526) в hudson.model.Run.execute(Run.java:1895) в hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:44) в hudson.model.ResourceController.execute(ResourceController.java:101) в hudson.model.Executor.run(Executor.java:442) Шаг сборки «HTTP-запрос» помечен как неудачный
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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