REST API выдает NoSuchMethodError после реализации Spring Security ⇐ JAVA
-
Гость
REST API выдает NoSuchMethodError после реализации Spring Security
Я изучаю Java и создаю REST API. Конечные точки базового контроллера работают, когда я вызываю их через Postman перед реализацией Spring Security.
Я хотел реализовать Spring Security и прошел руководство.
После реализации всего я попытался снова вызвать конечные точки, но получаю эту ошибку:
2024-02-27T18:06:15.155+01:00 ОШИБКА 29804 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() для сервлета [dispatcherServlet] в контексте с путем [] выдал исключение [выполнение сервлета выдало исключение] с основной причиной
java.lang.NoSuchMethodError: 'логическое значение org.springframework.security.authentication.AuthenticationTrustResolver.isAuthenticated(org.springframework.security.core.Authentication)'
…а затем очень длинная трассировка стека, которую я пытался проанализировать, но для новичка это слишком сложно.
2024-02-27T18:06:15.155+01:00 ОШИБКА 29804 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service( ) для сервлета [dispatcherServlet] в контексте с путем [] выдало исключение [выполнение сервлета выдало исключение] с основной причиной java.lang.NoSuchMethodError: 'boolean org.springframework.security.authentication.AuthenticationTrustResolver.isAuthentication(org.springframework.security.core.Authentication)' в org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getAuthentication(SecurityContextHolderAwareRequestWrapper.java:96) ~[spring- security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getUserPrincipal(SecurityContextHolderAwareRequestWrapper.java:127) ~[spring-security-web-6.2.2.jar:6.2 .2] в org.springframework.web.servlet.FrameworkServlet.getUsernameForRequest(FrameworkServlet.java:1167) ~[spring-webmvc-6.1.3.jar:6.1.3] в org.springframework.web.servlet.FrameworkServlet.publishRequestHandledEvent (FrameworkServlet.java:1152) ~[spring-webmvc-6.1.3.jar:6.1.3] в org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1031) ~[spring-webmvc-6.1. 3.jar:6.1.3] по адресу org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903) ~[spring-webmvc-6.1.3.jar:6.1.3] по адресу jakarta.servlet.http. HttpServlet.service(HttpServlet.java:564) ~[tomcat-embed-core-10.1.18.jar:6.0] в org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) ~[spring-webmvc -6.1.3.jar:6.1.3] в jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658) ~[tomcat-embed-core-10.1.18.jar:6.0] в org.apache.catalina .core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) ~[tomcat-embed-websocket-10.1.18 .jar:10.1.18] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina .core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.springframework.web.filter.CompositeFilter$VirtualFilterChain.doFilter(CompositeFilter.java: 108) ~[spring-web-6.1.3.jar:6.1.3] по адресу org.springframework.security.web.FilterChainProxy.lambda$doFilterInternal$3(FilterChainProxy.java:231) ~[spring-security-web-6.2. 2.jar:6.2.2] по адресу org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:365) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org. Springframework.security.web.access.intercept.AuthorizationFilter.doFilter(AuthorizationFilter.java:100) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.FilterChainProxy$VirtualFilterChain .doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:126) ~[ Spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:120) ~[spring-security-web-6.2.2.jar :6.2.2] по адресу org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security .web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:100) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy. java:374) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:179) ~[spring-security-web -6.2.2.jar:6.2.2] по адресу org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.FilterChainProxy$ VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:213 ) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar: 6.1.3] по адресу org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security. web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:107) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.authentication.logout.LogoutFilter.doFilter (LogoutFilter.java:93) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2 .jar:6.2.2] в org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:117) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework .web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java: 374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91) ~[spring-web-6.1.3.jar :6.1.3] в org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.security.web.FilterChainProxy $VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-6.2.2 .jar:6.2.2] в org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.security.web .FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.context.SecurityContextHolderFilter.doFilter(SecurityContextHolderFilter.java: 82) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.context.SecurityContextHolderFilter.doFilter(SecurityContextHolderFilter.java:69) ~[spring-security-web-6.2 .2.jar:6.2.2] в org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org .springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:62) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.web.filter. OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring -security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.session.DisableEncodeUrlFilter.doFilterInternal(DisableEncodeUrlFilter.java:42) ~[spring-security-web-6.2.2.jar: 6.2.2] по адресу org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] по адресу org.springframework.security.web.FilterChainProxy$ VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:233) ~[spring -security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:191) ~[spring-security-web-6.2.2.jar:6.2. 2] в org.springframework.web.filter.CompositeFilter$VirtualFilterChain.doFilter(CompositeFilter.java:113) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.web.servlet.handler. HandlerMappingIntrospector.lambda$createCacheFilter$3(HandlerMappingIntrospector.java:195) ~[spring-webmvc-6.1.3.jar:6.1.3] в org.springframework.web.filter.CompositeFilter$VirtualFilterChain.doFilter(CompositeFilter.java:113) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.web.filter.CompositeFilter.doFilter(CompositeFilter.java:74) ~[spring-web-6.1.3.jar:6.1.3 ] в org.springframework.security.config.annotation.web.configuration.WebMvcSecurityConfiguration$CompositeFilterChainProxy.doFilter(WebMvcSecurityConfiguration.java:230) ~[spring-security-config-6.2.2.jar:6.2.2] в org.springframework .web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:352) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:268) ~[spring-web-6.1.3.jar:6.1.3] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.18.jar:10.1 .18] в org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.springframework.web.filter.RequestContextFilter .doFilterInternal(RequestContextFilter.java:100) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web- 6.1.3.jar:6.1.3] по адресу org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.18.jar:10.1.18] по адресу org. apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-6.1.3.jar:6.1 .3] в org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed- core-10.1.18.jar:10.1.18] по адресу org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-6.1.3.jar:6.1.3] по адресу org. Springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174 ) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.18. jar:10.1.18] в org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina. core.StandardContextValve.invoke(StandardContextValve.java:90) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482) ~ [tomcat-embed-core-10.1.18.jar:10.1.18] по адресу org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115) ~[tomcat-embed-core-10.1.18.jar: 10.1.18] по адресу org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) ~[tomcat-embed-core-10.1.18.jar:10.1.18] по адресу org.apache.catalina.core. StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340) ~[tomcat -embed-core-10.1.18.jar:10.1.18] по адресу org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391) ~[tomcat-embed-core-10.1.18.jar:10.1. 18] в org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.coyote.AbstractProtocol$ConnectionHandler.process( AbstractProtocol.java:896) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744) ~[tomcat -embed-core-10.1.18.jar:10.1.18] по адресу org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) ~[tomcat-embed-core-10.1.18.jar: 10.1.18] в org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.tomcat. util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run (TaskThread.java:61) ~[tomcat-embed-core-10.1.18.jar:10.1.18] по адресу java.base/java.lang.Thread.run(Thread.java:1583) ~[na:na] Это моя конфигурация безопасности
пакет org.cogip.cogiprestapi.config; импортировать org.springframework.context.annotation.Bean; импортировать org.springframework.context.annotation.Configuration; импортировать org.springframework.security.config.Customizer; импортировать org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; импортировать org.springframework.security.config.annotation.web.builders.HttpSecurity; импортировать org.springframework.security.core.userdetails.User; импортировать org.springframework.security.core.userdetails.UserDetails; импортировать org.springframework.security.core.userdetails.UserDetailsService; импортировать org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; импортировать org.springframework.security.crypto.password.PasswordEncoder; импортировать org.springframework.security.provisioning.InMemoryUserDetailsManager; импортировать org.springframework.security.web.SecurityFilterChain; @Конфигурация @EnableMethodSecurity общественный класс SecurityConfig { @Бин SecurityFilterChain securityFilterChain (HttpSecurity httpSecurity) выдает исключение { httpSecurity.csrf(Customizer.withDefaults()) .authorizeHttpRequests((authorizeObj) -> { авторизироватьОбж.любойЗапрос().аутентифицированный(); }).httpBasic(Customizer.withDefaults()); вернуть httpSecurity.build(); } @Бин общедоступный PasswordEncoder парольEncoder() { вернуть новый BCryptPasswordEncoder(); } @Бин общественный UserDetailsService userDetailsService () { UserDetails admin = User.builder() .имя_пользователя("администратор") .password(passwordEncoder().encode("admin")) .roles("АДМИН") .строить(); Бухгалтер UserDetails = User.builder() .username("бухгалтер") .password(passwordEncoder().encode("бухгалтер")) .roles("БУХГАЛТЕР") .строить(); Стажер UserDetails = User.builder() .username("стажер") .password(passwordEncoder().encode("стажер")) .roles("СТАЖЕР") .строить(); вернуть новый InMemoryUserDetailsManager(администратор, бухгалтер, стажер); } } А это мой класс RestController:
пакет org.cogip.cogiprestapi.controllers; импортировать org.cogip.cogiprestapi.repositories.ContactRepository; импортировать org.springframework.http.HttpStatus; импортировать org.springframework.http.ResponseEntity; импортировать org.springframework.security.access.prepost.PreAuthorize; импортировать org.springframework.web.bind.annotation.*; импортировать org.cogip.cogiprestapi.model.Contact; импортировать org.cogip.cogiprestapi.services.ContactService; импортировать java.util.List; @RestController @RequestMapping ("/контакты") общественный класс ContactController { частный окончательный ContactService contactService; общественный ContactController (ContactService contactService) { this.contactService = contactService; } @GetMapping публичный список getAllContact() { верните this.contactService.getAllContacts(); } @PreAuthorize("hasAnyRole('АДМИН', 'БУХГАЛТЕР')") @GetMapping ("/search") общедоступный список getContactsByFilters( @RequestParam (обязательно = false) Целочисленный идентификатор, @RequestParam (обязательно = false) Строковое имя, @RequestParam (обязательно = false) Строковая фамилия, @RequestParam (обязательно = false) Строка телефона, @RequestParam (обязательно = false) Целочисленный идентификатор компании ){ вернуть this.contactService.getContactsByFilters(id, имя, фамилия, телефон, идентификатор компании); } @PreAuthorize("hasAnyRole('АДМИН', 'БУХГАЛТЕР')") @PostMapping ("/добавить") public ResponseEntity addContact(@RequestBody Контактный контакт){ this.contactService.addContact(контакт); вернуть ResponseEntity .status(HttpStatus.OK) .body("Контакт " + contact.getFirstname() + " " + contact.getLastname() + " был успешно добавлен."); } @PreAuthorize("hasAnyRole('АДМИН', 'БУХГАЛТЕР')") @PutMapping ("/update/{id}") public ResponseEntity updateContact(@PathVariable("id") int id, @RequestBody Контактный контакт){ Контакт обновленныйКонтакт = this.contactService.updateContact(id, контакт); вернуть ResponseEntity .status(HttpStatus.OK) .body(обновленныйКонтакт); } @PreAuthorize("hasAnyRole('АДМИН', 'БУХГАЛТЕР')") @DeleteMapping("/delete/{id}") public ResponseEntity deleteContact(@PathVariable("id") int id){ this.contactService.deleteContact(id); вернуть ResponseEntity .status(HttpStatus.OK) .body("Контакт с идентификатором " + id + " успешно удален."); } } Я уже искал пару часов. Одно из предложений, которое продолжает появляться снова, заключается в том, что я использую несовместимые зависимости. Плагин Maven Helper с анализатором зависимостей не обнаруживает конфликтов.
Я поискал во внешних библиотеках:
AuthenticationTrustResolver в org.springframework.security.authentication не имеет метода isAuthenticated(), а только метода isFullyAuthenticated().
org.springframework.security:spring-security-core:6.2.1 существует интерфейс, который определяет логическое значение isAuthenticated();
Но я не уверен, как именно это интерпретировать.
Несмотря на то, что плагин Maven Helper сообщает, что с зависимостями проблем нет; Я думаю, что это почти должно быть? Это то, с чем я сталкивался практически в любой подобной проблеме.
Но я на исходе. Я не знаю, как дальше проверять и оценивать.
Это мой pom.xml:
4.0.0 org.springframework.boot spring-boot-starter-parent 3.2.2 org.thibault cogip-rest-api 0.0.1-SNAPSHOT cogip-rest-api Rest API для проекта BeCode COGIP 17 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-jdbc 3.2.2 mysql mysql-connector-java 8.0.33 время выполнения org.springframework.boot spring-boot-starter-test тест org.springframework.security spring-security-web 6.2.2 org.springframework.security spring-security-config 6.2.2 org.springframework.boot spring-boot-maven-plugin Надеюсь, я предоставил всю необходимую информацию. Я ценю любую помощь.
Спасибо
Я изучаю Java и создаю REST API. Конечные точки базового контроллера работают, когда я вызываю их через Postman перед реализацией Spring Security.
Я хотел реализовать Spring Security и прошел руководство.
После реализации всего я попытался снова вызвать конечные точки, но получаю эту ошибку:
2024-02-27T18:06:15.155+01:00 ОШИБКА 29804 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() для сервлета [dispatcherServlet] в контексте с путем [] выдал исключение [выполнение сервлета выдало исключение] с основной причиной
java.lang.NoSuchMethodError: 'логическое значение org.springframework.security.authentication.AuthenticationTrustResolver.isAuthenticated(org.springframework.security.core.Authentication)'
…а затем очень длинная трассировка стека, которую я пытался проанализировать, но для новичка это слишком сложно.
2024-02-27T18:06:15.155+01:00 ОШИБКА 29804 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service( ) для сервлета [dispatcherServlet] в контексте с путем [] выдало исключение [выполнение сервлета выдало исключение] с основной причиной java.lang.NoSuchMethodError: 'boolean org.springframework.security.authentication.AuthenticationTrustResolver.isAuthentication(org.springframework.security.core.Authentication)' в org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getAuthentication(SecurityContextHolderAwareRequestWrapper.java:96) ~[spring- security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getUserPrincipal(SecurityContextHolderAwareRequestWrapper.java:127) ~[spring-security-web-6.2.2.jar:6.2 .2] в org.springframework.web.servlet.FrameworkServlet.getUsernameForRequest(FrameworkServlet.java:1167) ~[spring-webmvc-6.1.3.jar:6.1.3] в org.springframework.web.servlet.FrameworkServlet.publishRequestHandledEvent (FrameworkServlet.java:1152) ~[spring-webmvc-6.1.3.jar:6.1.3] в org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1031) ~[spring-webmvc-6.1. 3.jar:6.1.3] по адресу org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903) ~[spring-webmvc-6.1.3.jar:6.1.3] по адресу jakarta.servlet.http. HttpServlet.service(HttpServlet.java:564) ~[tomcat-embed-core-10.1.18.jar:6.0] в org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) ~[spring-webmvc -6.1.3.jar:6.1.3] в jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658) ~[tomcat-embed-core-10.1.18.jar:6.0] в org.apache.catalina .core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) ~[tomcat-embed-websocket-10.1.18 .jar:10.1.18] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina .core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.springframework.web.filter.CompositeFilter$VirtualFilterChain.doFilter(CompositeFilter.java: 108) ~[spring-web-6.1.3.jar:6.1.3] по адресу org.springframework.security.web.FilterChainProxy.lambda$doFilterInternal$3(FilterChainProxy.java:231) ~[spring-security-web-6.2. 2.jar:6.2.2] по адресу org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:365) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org. Springframework.security.web.access.intercept.AuthorizationFilter.doFilter(AuthorizationFilter.java:100) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.FilterChainProxy$VirtualFilterChain .doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:126) ~[ Spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:120) ~[spring-security-web-6.2.2.jar :6.2.2] по адресу org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security .web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:100) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy. java:374) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:179) ~[spring-security-web -6.2.2.jar:6.2.2] по адресу org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.FilterChainProxy$ VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:213 ) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar: 6.1.3] по адресу org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security. web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:107) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.authentication.logout.LogoutFilter.doFilter (LogoutFilter.java:93) ~[spring-security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2 .jar:6.2.2] в org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:117) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework .web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java: 374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91) ~[spring-web-6.1.3.jar :6.1.3] в org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.security.web.FilterChainProxy $VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-6.2.2 .jar:6.2.2] в org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.security.web .FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.context.SecurityContextHolderFilter.doFilter(SecurityContextHolderFilter.java: 82) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.context.SecurityContextHolderFilter.doFilter(SecurityContextHolderFilter.java:69) ~[spring-security-web-6.2 .2.jar:6.2.2] в org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org .springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:62) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.web.filter. OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring -security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.session.DisableEncodeUrlFilter.doFilterInternal(DisableEncodeUrlFilter.java:42) ~[spring-security-web-6.2.2.jar: 6.2.2] по адресу org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] по адресу org.springframework.security.web.FilterChainProxy$ VirtualFilterChain.doFilter(FilterChainProxy.java:374) ~[spring-security-web-6.2.2.jar:6.2.2] в org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:233) ~[spring -security-web-6.2.2.jar:6.2.2] по адресу org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:191) ~[spring-security-web-6.2.2.jar:6.2. 2] в org.springframework.web.filter.CompositeFilter$VirtualFilterChain.doFilter(CompositeFilter.java:113) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.web.servlet.handler. HandlerMappingIntrospector.lambda$createCacheFilter$3(HandlerMappingIntrospector.java:195) ~[spring-webmvc-6.1.3.jar:6.1.3] в org.springframework.web.filter.CompositeFilter$VirtualFilterChain.doFilter(CompositeFilter.java:113) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.web.filter.CompositeFilter.doFilter(CompositeFilter.java:74) ~[spring-web-6.1.3.jar:6.1.3 ] в org.springframework.security.config.annotation.web.configuration.WebMvcSecurityConfiguration$CompositeFilterChainProxy.doFilter(WebMvcSecurityConfiguration.java:230) ~[spring-security-config-6.2.2.jar:6.2.2] в org.springframework .web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:352) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:268) ~[spring-web-6.1.3.jar:6.1.3] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.18.jar:10.1 .18] в org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.springframework.web.filter.RequestContextFilter .doFilterInternal(RequestContextFilter.java:100) ~[spring-web-6.1.3.jar:6.1.3] в org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web- 6.1.3.jar:6.1.3] по адресу org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.18.jar:10.1.18] по адресу org. apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-6.1.3.jar:6.1 .3] в org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed- core-10.1.18.jar:10.1.18] по адресу org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-6.1.3.jar:6.1.3] по адресу org. Springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.1.3.jar:6.1.3] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174 ) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.18. jar:10.1.18] в org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina. core.StandardContextValve.invoke(StandardContextValve.java:90) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482) ~ [tomcat-embed-core-10.1.18.jar:10.1.18] по адресу org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115) ~[tomcat-embed-core-10.1.18.jar: 10.1.18] по адресу org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) ~[tomcat-embed-core-10.1.18.jar:10.1.18] по адресу org.apache.catalina.core. StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340) ~[tomcat -embed-core-10.1.18.jar:10.1.18] по адресу org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391) ~[tomcat-embed-core-10.1.18.jar:10.1. 18] в org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.coyote.AbstractProtocol$ConnectionHandler.process( AbstractProtocol.java:896) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744) ~[tomcat -embed-core-10.1.18.jar:10.1.18] по адресу org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) ~[tomcat-embed-core-10.1.18.jar: 10.1.18] в org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.tomcat. util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-10.1.18.jar:10.1.18] в org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run (TaskThread.java:61) ~[tomcat-embed-core-10.1.18.jar:10.1.18] по адресу java.base/java.lang.Thread.run(Thread.java:1583) ~[na:na] Это моя конфигурация безопасности
пакет org.cogip.cogiprestapi.config; импортировать org.springframework.context.annotation.Bean; импортировать org.springframework.context.annotation.Configuration; импортировать org.springframework.security.config.Customizer; импортировать org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; импортировать org.springframework.security.config.annotation.web.builders.HttpSecurity; импортировать org.springframework.security.core.userdetails.User; импортировать org.springframework.security.core.userdetails.UserDetails; импортировать org.springframework.security.core.userdetails.UserDetailsService; импортировать org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; импортировать org.springframework.security.crypto.password.PasswordEncoder; импортировать org.springframework.security.provisioning.InMemoryUserDetailsManager; импортировать org.springframework.security.web.SecurityFilterChain; @Конфигурация @EnableMethodSecurity общественный класс SecurityConfig { @Бин SecurityFilterChain securityFilterChain (HttpSecurity httpSecurity) выдает исключение { httpSecurity.csrf(Customizer.withDefaults()) .authorizeHttpRequests((authorizeObj) -> { авторизироватьОбж.любойЗапрос().аутентифицированный(); }).httpBasic(Customizer.withDefaults()); вернуть httpSecurity.build(); } @Бин общедоступный PasswordEncoder парольEncoder() { вернуть новый BCryptPasswordEncoder(); } @Бин общественный UserDetailsService userDetailsService () { UserDetails admin = User.builder() .имя_пользователя("администратор") .password(passwordEncoder().encode("admin")) .roles("АДМИН") .строить(); Бухгалтер UserDetails = User.builder() .username("бухгалтер") .password(passwordEncoder().encode("бухгалтер")) .roles("БУХГАЛТЕР") .строить(); Стажер UserDetails = User.builder() .username("стажер") .password(passwordEncoder().encode("стажер")) .roles("СТАЖЕР") .строить(); вернуть новый InMemoryUserDetailsManager(администратор, бухгалтер, стажер); } } А это мой класс RestController:
пакет org.cogip.cogiprestapi.controllers; импортировать org.cogip.cogiprestapi.repositories.ContactRepository; импортировать org.springframework.http.HttpStatus; импортировать org.springframework.http.ResponseEntity; импортировать org.springframework.security.access.prepost.PreAuthorize; импортировать org.springframework.web.bind.annotation.*; импортировать org.cogip.cogiprestapi.model.Contact; импортировать org.cogip.cogiprestapi.services.ContactService; импортировать java.util.List; @RestController @RequestMapping ("/контакты") общественный класс ContactController { частный окончательный ContactService contactService; общественный ContactController (ContactService contactService) { this.contactService = contactService; } @GetMapping публичный список getAllContact() { верните this.contactService.getAllContacts(); } @PreAuthorize("hasAnyRole('АДМИН', 'БУХГАЛТЕР')") @GetMapping ("/search") общедоступный список getContactsByFilters( @RequestParam (обязательно = false) Целочисленный идентификатор, @RequestParam (обязательно = false) Строковое имя, @RequestParam (обязательно = false) Строковая фамилия, @RequestParam (обязательно = false) Строка телефона, @RequestParam (обязательно = false) Целочисленный идентификатор компании ){ вернуть this.contactService.getContactsByFilters(id, имя, фамилия, телефон, идентификатор компании); } @PreAuthorize("hasAnyRole('АДМИН', 'БУХГАЛТЕР')") @PostMapping ("/добавить") public ResponseEntity addContact(@RequestBody Контактный контакт){ this.contactService.addContact(контакт); вернуть ResponseEntity .status(HttpStatus.OK) .body("Контакт " + contact.getFirstname() + " " + contact.getLastname() + " был успешно добавлен."); } @PreAuthorize("hasAnyRole('АДМИН', 'БУХГАЛТЕР')") @PutMapping ("/update/{id}") public ResponseEntity updateContact(@PathVariable("id") int id, @RequestBody Контактный контакт){ Контакт обновленныйКонтакт = this.contactService.updateContact(id, контакт); вернуть ResponseEntity .status(HttpStatus.OK) .body(обновленныйКонтакт); } @PreAuthorize("hasAnyRole('АДМИН', 'БУХГАЛТЕР')") @DeleteMapping("/delete/{id}") public ResponseEntity deleteContact(@PathVariable("id") int id){ this.contactService.deleteContact(id); вернуть ResponseEntity .status(HttpStatus.OK) .body("Контакт с идентификатором " + id + " успешно удален."); } } Я уже искал пару часов. Одно из предложений, которое продолжает появляться снова, заключается в том, что я использую несовместимые зависимости. Плагин Maven Helper с анализатором зависимостей не обнаруживает конфликтов.
Я поискал во внешних библиотеках:
AuthenticationTrustResolver в org.springframework.security.authentication не имеет метода isAuthenticated(), а только метода isFullyAuthenticated().
org.springframework.security:spring-security-core:6.2.1 существует интерфейс, который определяет логическое значение isAuthenticated();
Но я не уверен, как именно это интерпретировать.
Несмотря на то, что плагин Maven Helper сообщает, что с зависимостями проблем нет; Я думаю, что это почти должно быть? Это то, с чем я сталкивался практически в любой подобной проблеме.
Но я на исходе. Я не знаю, как дальше проверять и оценивать.
Это мой pom.xml:
4.0.0 org.springframework.boot spring-boot-starter-parent 3.2.2 org.thibault cogip-rest-api 0.0.1-SNAPSHOT cogip-rest-api Rest API для проекта BeCode COGIP 17 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-jdbc 3.2.2 mysql mysql-connector-java 8.0.33 время выполнения org.springframework.boot spring-boot-starter-test тест org.springframework.security spring-security-web 6.2.2 org.springframework.security spring-security-config 6.2.2 org.springframework.boot spring-boot-maven-plugin Надеюсь, я предоставил всю необходимую информацию. Я ценю любую помощь.
Спасибо
Мобильная версия