JAVA + SpringSecurity + Ошибка создания bean-компонента с именем «securityConfig»: не удалось внедрить автоматически подJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 JAVA + SpringSecurity + Ошибка создания bean-компонента с именем «securityConfig»: не удалось внедрить автоматически под

Сообщение Anonymous »

Я делаю небольшой проект на JAVA, использую Spring Security для аутентификации, но когда я пытаюсь запустить свой код, он выдает следующий стек ошибок:

org.springframework.beans.factory.UnsatisfiedDependencyException: ошибка создания bean-компонента с именем 'adminUserConfig', определенным в файле [C:\Users\Matheus Castilho\Desktop\projetos\BookStoreAPI\target\classes\com\br \BookStoreAPI\config\AdminUserConfig.class]: неудовлетворительная зависимость, выраженная через параметр конструктора 2: ошибка создания bean-компонента с именем «securityConfig»: не удалось внедрить автоматически подключенные зависимости
в org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray (ConstructorResolver.java:795) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:237) ~[ Spring-beans-6.1.6.jar:6.1.6]
на org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1355) ~[spring-beans-6.1.6.jar :6.1.6]
на org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1192) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework.beans.factory. support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0( AbstractBeanFactory.java:326) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring -beans-6.1.6.jar:6.1.6]
на org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.1.6.jar: 6.1.6]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:975) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework.context.support.AbstractApplicationContext .finishBeanFactoryInitialization(AbstractApplicationContext.java:962) ~[spring-context-6.1.6.jar:6.1.6]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:624) ~[ Spring-context-6.1.6.jar:6.1.6]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.2.5 .jar:3.2.5]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-3.2.5.jar:3.2.5]
at org .springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456) ~[spring-boot-3.2.5.jar:3.2.5]
в org.springframework.boot.SpringApplication.run(SpringApplication.java: 334) ~[spring-boot-3.2.5.jar:3.2.5]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1354) ~[spring-boot-3.2.5.jar :3.2.5]
в org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-3.2.5.jar:3.2.5]
в com.br .BookStoreAPI.BookStoreApiApplication.main(BookStoreApiApplication.java:10) ~[classes/:na]
Вызвано: org.springframework.beans.factory.BeanCreationException: ошибка создания bean-компонента с именем 'securityConfig': внедрение автоматически подключенных зависимостей не удалось
в org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:514) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework .beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1419) ~[spring-beans-6.1.6.jar:6.1.6]
на org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory. doCreateBean(AbstractAutowireCapableBeanFactory.java:599) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~ [spring-beans-6.1.6.jar:6.1.6]
на org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.1 .6.jar:6.1.6]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework. beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod (ConstructorResolver.java:409) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1335) ~[ Spring-beans-6.1.6.jar:6.1.6]
на org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1165) ~[spring-beans-6.1.6.jar :6.1.6]
на org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework.beans.factory. support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton( DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring -beans-6.1.6.jar:6.1.6]
на org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.1.6.jar: 6.1.6]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1443) ~[spring-beans-6.1.6.jar:6.1.6]
на org.springframework.beans.factory.support .DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1353) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java: 904) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:782) ~[spring-beans-6.1 .6.jar:6.1.6]
... Пропущено 19 общих фреймов
Причина: java.lang.IllegalArgumentException: не удалось разрешить заполнитель «PUBLIC_KEY» в значении «${PUBLIC_KEY}»
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:180) ~[spring-core-6.1.6.jar:6.1.6]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders( PropertyPlaceholderHelper.java:126) ~[spring-core-6.1.6.jar:6.1.6]
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core -6.1.6.jar:6.1.6]
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-6.1.6.jar:6.1.6]
в org.springframework.core.env.AbstractPropertyResolver.resolveNestedPlaceholders(AbstractPropertyResolver.java:230) ~[spring-core-6.1.6.jar:6.1.6]
в org.springframework.boot. context.properties.source.ConfigurationPropertySourcesPropertyResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:80) ~[spring-boot-3.2.5.jar:3.2.5]
в org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver .getProperty(ConfigurationPropertySourcesPropertyResolver.java:61) ~[spring-boot-3.2.5.jar:3.2.5]
at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:552) ~[ Spring-core-6.1.6.jar:6.1.6]
на org.springframework.context.support.PropertySourcesPlaceholderConfigurer$1.getProperty(PropertySourcesPlaceholderConfigurer.java:153) ~[spring-context-6.1.6.jar: 6.1.6]
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$1.getProperty(PropertySourcesPlaceholderConfigurer.java:149) ~[spring-context-6.1.6.jar:6.1.6]
at org .springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:85) ~[spring-core-6.1.6.jar:6.1.6]
at org.springframework.core.env.PropertySourcesPropertyResolver.getPropertyAsRawString( PropertySourcesPropertyResolver.java:74) ~[spring-core-6.1.6.jar:6.1.6]
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:153) ~[spring-core-6.1 .6.jar:6.1.6]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-6.1.6.jar:6.1.6]
в org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core-6.1.6.jar:6.1.6]
в org.springframework.core.env.AbstractPropertyResolver. solveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-6.1.6.jar:6.1.6]
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:200) ~[spring-context-6.1.6.jar:6.1.6]
в org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:953) ~[spring-beans-6.1.6 .jar:6.1.6]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1374) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1353) ~[spring-beans-6.1.6.jar:6.1.6]
в org.springframework.beans. Factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:784) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$Auto проводное полеэлемент .inject(AutowiredAnnotationBeanPostProcessor.java:767) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:145) ~[spring-beans-6.1.6.jar:6.1.6]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:508) ~[spring-beans-6.1.6 .jar:6.1.6]
... 40 общих фреймов опущены

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

Код: Выделить всё

package com.br.BookStoreAPI.config;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.web.SecurityFilterChain;

import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Value("${jwt.public}")
private String publicKey;
@Value("${jwt.private}")
private String privateKey;

@Bean
public RSAPublicKey rsaPublicKey() throws Exception {
String cleanedKey = publicKey
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s+", "");

if (cleanedKey.startsWith("ssh-rsa")) {
String[] parts = cleanedKey.split("\\s+");
if (parts.length >= 2) {
cleanedKey = parts[1];
} else {
throw new IllegalArgumentException("Formato de chave ssh-rsa inválido");
}
}

System.out.println("Public Key (cleaned): " + cleanedKey); // Para debug

byte[] decoded = Base64.getDecoder().decode(cleanedKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}

@Bean
public RSAPrivateKey rsaPrivateKey() throws Exception {
String privateKeyPEM = privateKey
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+", "");

System.out.println("Private Key PEM: " + privateKeyPEM); // Para debug

byte[] encoded = Base64.getMimeDecoder().decode(privateKeyPEM);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorize -> authorize
.requestMatchers(HttpMethod.POST, "/login").permitAll()
.requestMatchers(HttpMethod.POST, "/api/users/register").permitAll()
.anyRequest().authenticated())
.csrf(csrf -> csrf.disable())
.oauth2ResourceServer( oauth2 -> oauth2.jwt(Customizer.withDefaults()))
.sessionManagement(session ->  session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
@Bean
JwtDecoder jwtDecoder() throws Exception {
return NimbusJwtDecoder.withPublicKey(rsaPublicKey()).build();
}

@Bean
JwtEncoder jwtEncoder() throws Exception {
RSAKey key = new RSAKey.Builder(rsaPublicKey()).privateKey(rsaPrivateKey()).build();
ImmutableJWKSet keys = new ImmutableJWKSet(new JWKSet(key));
return new NimbusJwtEncoder(keys);
}

@Bean
PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
И My Pom XML вот так:

Код: Выделить всё

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0

org.springframework.boot
spring-boot-starter-parent
3.2.5
  

com.br
BookStoreAPI
0.0.1-SNAPSHOT
BookStoreAPI
Demo project for Spring Boot

17



org.springframework.boot
spring-boot-starter-data-jpa


org.springframework.boot
spring-boot-starter-oauth2-resource-server


org.springframework.boot
spring-boot-starter-security


org.springframework.boot
spring-boot-starter-web



jakarta.validation
jakarta.validation-api
3.0.0



com.mysql
mysql-connector-j
runtime


org.projectlombok
lombok
true


org.springframework.boot
spring-boot-starter-test
test


org.springframework.security
spring-security-test
test


org.springframework.boot
spring-boot-starter-security


io.jsonwebtoken
jjwt-jackson
0.12.6
runtime



io.jsonwebtoken
jjwt-impl
0.12.6
runtime



io.jsonwebtoken
jjwt-api
0.12.6






org.springframework.boot
spring-boot-maven-plugin



org.projectlombok
lombok









Я уже снова загрузил зависимости, надеясь, что это так, но получил ту же ошибку.


Подробнее здесь: https://stackoverflow.com/questions/791 ... g-injectio
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

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

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