2
respostas

Estou com problema para subir a aplicação no Spring, devido um erro na Classe WebSecurityConfig

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.core.userdetails.UserDetailsService]: Factory method 'userDetailsService' threw exception; nested exception is java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.provisioning.JdbcUserDetailsManagerConfigurer@63039a77 to already built object at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.20.jar:5.3.20] at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.20.jar:5.3.20] ... 78 common frames omitted Caused by: java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.provisioning.JdbcUserDetailsManagerConfigurer@63039a77 to already built object at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.add(AbstractConfiguredSecurityBuilder.java:182) ~[spring-security-config-5.7.1.jar:5.7.1] at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.apply(AbstractConfiguredSecurityBuilder.java:125) ~[spring-security-config-5.7.1.jar:5.7.1] at org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder.apply(AuthenticationManagerBuilder.java:280) ~[spring-security-config-5.7.1.jar:5.7.1] at org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder.jdbcAuthentication(AuthenticationManagerBuilder.java:160) ~[spring-security-config-5.7.1.jar:5.7.1] at org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration$DefaultPasswordEncoderAuthenticationManagerBuilder.jdbcAuthentication(AuthenticationConfiguration.java:285) ~[spring-security-config-5.7.1.jar:5.7.1] at br.com.alura.mvc.mudi.WebSecurityConfig.userDetailsService(WebSecurityConfig.java:52) ~[classes/:na] at br.com.alura.mvc.mudi.WebSecurityConfig$$EnhancerBySpringCGLIB$$4b513f8c.CGLIB$userDetailsService$1() ~[classes/:na] at br.com.alura.mvc.mudi.WebSecurityConfig$$EnhancerBySpringCGLIB$$4b513f8c$$FastClassBySpringCGLIB$$ae28b3b8.invoke() ~[classes/:na] at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.3.20.jar:5.3.20] at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.3.20.jar:5.3.20] at br.com.alura.mvc.mudi.WebSecurityConfig$$EnhancerBySpringCGLIB$$4b513f8c.userDetailsService() ~[classes/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.20.jar:5.3.20] ... 79 common frames omitted

2 respostas

package br.com.alura.mvc.mudi;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain;

@Configuration @EnableWebSecurity public class WebSecurityConfig {

@Autowired
private DataSource dataSource;

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
    .authorizeRequests()
    .anyRequest()
    .authenticated()
    .and()
    .formLogin(form -> form
            .loginPage("/login")
            .permitAll()).logout(logout -> logout.logoutUrl("/logout"));

    return http.build();

}

@Autowired
@Bean
public UserDetailsService userDetailsService(AuthenticationManagerBuilder auth) throws Exception {
    BCryptPasswordEncoder enconder = new BCryptPasswordEncoder();

    UserDetails user =
         User.builder()
            .username("joao")
            .password(enconder.encode("joao"))
            .roles("ADM")
            .build();

    auth.jdbcAuthentication()
    .dataSource(dataSource)
    .passwordEncoder(enconder).withUser(user);

    return new InMemoryUserDetailsManager(user);
}

}

Olá, Arthemyo!

O erro que você está enfrentando é causado pela tentativa de aplicar uma configuração de usuário JDBC a um objeto que já foi construído. Isso pode acontecer se você tentar aplicar a mesma configuração duas vezes ou se houver conflitos entre as configurações.

Para resolver esse problema, você pode tentar verificar se a configuração de usuário JDBC já foi aplicada em algum outro lugar do código e removê-la ou substituí-la por uma configuração diferente. Além disso, verifique se você está aplicando a configuração corretamente e se não há conflitos com outras configurações.

Caso você precise de mais ajuda, sugiro que poste mais informações sobre o seu código, como a classe WebSecurityConfig e as configurações de segurança que você está usando. Dessa forma, poderemos ajudá-lo com mais precisão.

Espero ter ajudado e bons estudos!