PatternParseException в моем загрузочном приложении SpringJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Гость
 PatternParseException в моем загрузочном приложении Spring

Сообщение Гость »


Я выполняю миграцию с приложения Spring boot 2 на Spring boot 3, Я внес все изменения в Spring Security, и приложение запустилось нормально. Когда я вызываю свою конечную точку, я получаю исключение PatternParseException и думаю, что это из-за моей конфигурации Spring Security.

Вы можете найти ниже мою конфигурацию безопасности Spring и веб-конфигурацию.

org.springframework.web.util.pattern.PatternParseException: больше данных шаблона не разрешено после {*...} или ** элемента шаблона в org.springframework.web.util.pattern.InternalPathPatternParser.peekDoubleWildcard(InternalPathPatternParser.java:250) ~[spring-web-6.0.11.jar!/:6.0.11] в org.springframework.web.util.pattern.InternalPathPatternParser.parse(InternalPathPatternParser.java:113) ~[spring-web-6.0.11.jar!/:6.0.11] в org.springframework.web.util.pattern.PathPatternParser.parse(PathPatternParser.java:129) ~[spring-web-6.0.11.jar!/:6.0.11] в org.springframework.web.servlet.handler.PathPatternMatchableHandlerMapping.lambda$match$0(PathPatternMatchableHandlerMapping.java:64) ~[spring-webmvc-6.0.11.jar!/:6.0.11] в java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1708) ~[na:na] Конфигурация безопасности

пакет com.omb.restcore.security; импортировать com.omb.core.security.utils.JasyptEncryptorDecryptor; импортировать org.apache.commons.lang3.StringUtils; импортировать org.springframework.beans.factory.annotation.Autowired; импортировать org.springframework.beans.factory.annotation.Value; импортировать org.springframework.context.annotation.Bean; импортировать org.springframework.context.annotation.Configuration; импортировать org.springframework.core.env.AbstractEnvironment; импортировать org.springframework.core.env.Environment; импортировать org.springframework.core.env.MapPropertySource; импортировать org.springframework.core.env.PropertySource; импортировать org.springframework.http.HttpMethod; импортировать org.springframework.security.config.Customizer; импортировать org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; импортировать org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer; импортировать org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; импортировать org.springframework.security.config.annotation.web.builders.HttpSecurity; импортировать org.springframework.security.web.SecurityFilterChain; импортировать org.springframework.web.cors.CorsConfiguration; импортировать org.springframework.web.cors.CorsConfigurationSource; импортировать org.springframework.web.cors.UrlBasedCorsConfigurationSource; импортировать java.util.Arrays; импортировать java.util.List; импортировать java.util.Map; импортировать java.util.logging.Logger; @Конфигурация @EnableGlobalMethodSecurity (prePostEnabled = true) общественный класс SecurityConfig { частный статический окончательный Logger LOG = Logger.getLogger(SecurityConfig.class.getName()); частная статическая окончательная строка HEALTHCHECK_URL = "/**/healthCheck"; частная статическая окончательная строка [] ALLOW_LIST = { HEALTHCHECK_URL, "/**/v3/api-docs", "/**/swagger-resources/**", "/**/swagger-ui.html", "/**/webjars/**", "/**/csrf", "/", "/**/css/**" }; @Value("${enableHttpAuthentication:true}") частное логическое значение EnableHttpAuthentication; @Value("${enableLoginEncryption}") частное логическое значение EnableLoginEncryption; @Value("${allowAnonymousAccessToSwaggerDoc}") частное логическое значениеallowAnonymousAccessToSwaggerDoc; @Autowired частная среда обитания; @Бин public SecurityFilterChain filterChain(HttpSecurity http) выдает исключение { если (enableHttpAuthentication) { // Принимаем только запросы, аутентифицированные BASIC, за исключением указанных ресурсов, которые доступны без // аутентификация если (allowAnonymousAccessToSwaggerDoc) { http.csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth.requestMatchers(ALLOW_LIST).permitAll() .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() .anyRequest().аутентифицированный()) .httpBasic(Customizer.withDefaults()); } еще { http.csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth.requestMatchers(HEALTHCHECK_URL).permitAll() .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() .anyRequest().аутентифицированный()) .httpBasic(Customizer.withDefaults()); } LOG.info("БАЗОВАЯ HTTP-аутентификация включена"); } еще { // Отключаем аутентификацию при использовании API http.csrf(csrf -> csrf.disable()) .authorizeHttpRequests(аутентификация -> auth.anyRequest().anonymous()); LOG.info("БАЗОВАЯ HTTP-аутентификация отключена"); } вернуть http.build(); } @Бин CorsConfigurationSource corsConfigurationSource() { Конфигурация CorsConfiguration = новая CorsConfiguration(); Configuration.setAllowedOrigins(List.of("*")); Configuration.setAllowedMethods(List.of("*")); Configuration.setAllowCredentials(истина); Configuration.setAllowedHeaders(Arrays.asList("Авторизация", "Тип запроса")); Configuration.setExposeHeaders(List.of("X-Get-Header")); Источник UrlBasedCorsConfigurationSource = новый UrlBasedCorsConfigurationSource (); source.registerCorsConfiguration("/**", конфигурация); источник возврата; } @Autowired public void configureGlobal (AuthenticationManagerBuilder auth) выдает исключение { InMemoryUserDetailsManagerConfigurer inMemoryAuth = auth.inMemoryAuthentication(); for (PropertySource propertySource: ((AbstractEnvironment) Environment).getPropertySources()) { если (propertySource экземпляр MapPropertySource) { Свойства Map = ((MapPropertySource) propertySource).getSource(); java.util.regex.Pattern шаблон = java.util.regex.Pattern.compile("user\\.(.*)\\.пароль"); for (String k: Properties.keySet()) { java.util.regex.Matcher matcher = шаблон.matcher(k); если (matcher.find()) { Строка user = matcher.group(1); Строка pwd = Properties.get(k).toString(); если (enableLoginEncryption) { пользователь = JasyptEncryptorDecryptor.decrypt(пользователь); } pwd = JasyptEncryptorDecryptor.decrypt(pwd); если (!StringUtils.isEmpty(pwd)) { LOG.finest("Настроены права доступа HTTP BASIC для пользователя " + user); inMemoryAuth.withUser(user).password("{noop}" + pwd).roles("ПОЛЬЗОВАТЕЛЬ"); } еще { LOG.finest("Отключены права доступа HTTP BASIC для пользователя " + user); } } } } } LOG.info("БАЗОВАЯ настройка HTTP завершена."); } } Вебконфигурация
пакет com.omb.gateway.security; импортировать org.springframework.context.annotation.Bean; импортировать org.springframework.context.annotation.Configuration; импортировать org.springframework.web.servlet.config.annotation.CorsRegistry; импортировать org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Конфигурация общественный класс WebConfig { @Бин общественный WebMvcConfigurer corsConfigurer () { вернуть новый WebMvcConfigurer() { @Override public void addCorsMappings (реестр CorsRegistry) { реестр.addMapping("/**") .allowedOriginPatterns("*") .allowedHeaders("Тип запроса") .exposeHeaders("X-Get-Header") .allowCredentials(истина); } }; } }
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

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

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