'Spring boot / Spring security with dedicated database for security

I am looking desesperatly for spring boot running with spring security configured with two different databases. One for application's data and the other one for spring security only.

I have worked with https://www.baeldung.com/spring-data-jpa-multiple-databases for multiple databases configurations.With that too https://www.laulem.com/dev/spring-boot/spring-security.html for spring security. But after several work, I'am unable to have a working project with spring boot and spring security with two separates database.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@PropertySource({"classpath:application.properties"})
@EnableJpaRepositories(
        basePackages = "com.myApp.security.repositories",
        entityManagerFactoryRef = "productEntityManager",
        transactionManagerRef = "productTransactionManager"
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Autowired
    private Environment env;
 
    @Autowired
    @Qualifier("userDetailsService")
    private UserDetailsService customUserDetailsService;
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests().antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/login").successHandler( myAuthenticationSuccessHandler() ).failureUrl("/login?error=true").permitAll()
                .and().logout().deleteCookies("JSESSIONID").logoutUrl("/logout").logoutSuccessUrl("/login");
    }
 
    @Override
    protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder.userDetailsService(customUserDetailsService).passwordEncoder(myAppPasswordEncoder());
    }
 
    /**
     * Cryptage des mots de passe
     *
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
 
 
    /**
     * No password encryption (dev only!!!)
     *
     * @return
     */
    @Bean
    public myAppPasswordEncoder myAppPasswordEncoder() {
        return new myAppPasswordEncoder();
    }
 
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
 
    @Bean
    public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
        return new myAppUrlAuthenticationSuccessHandler();
    }
 
    @Bean
    @ConfigurationProperties(prefix="spring.productdb-datasource")
    public DataSource productDataSource() {
        return DataSourceBuilder.create().build();
    }
 
    @Bean
    public LocalContainerEntityManagerFactoryBean productEntityManager() {
        final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(productDataSource());
        em.setPackagesToScan("com.myApp.security.metier.impl");
 
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        final HashMap<String, Object> properties = new HashMap<String, Object>();
        properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
        em.setJpaPropertyMap(properties);
 
        return em;
    }
 
    @Bean
    public PlatformTransactionManager productTransactionManager() {
        final JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(productEntityManager().getObject());
        return transactionManager;
    }
}

I get this kind of errors

org.springframework.beans.factory.UnsatisfiedDependencyException: 
    Error creating bean with name 'securityConfig': 
    Unsatisfied dependency expressed through field 'customUserDetailsService'; 
    nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 
    Error creating bean with name 'userDetailsService': 
    Unsatisfied dependency expressed through field 'userService'; 
    nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 
    Error creating bean with name 'userService': 
    Unsatisfied dependency expressed through field 'userRepository'; 
    nested exception is org.springframework.beans.factory.BeanCreationException: 
    Error creating bean with name 'userRepository' defined in com.myApp.security.repositories.UserRepository defined in @EnableJpaRepositories declared on SecurityConfig: 
    Cannot create inner bean '(inner bean)#2239ae10' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; 
    nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2239ae10': 
    Cannot resolve reference to bean 'productEntityManager' while setting constructor argument; 
    nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: 
    Error creating bean with name 'productEntityManager': Requested bean is currently in creation: 
    Is there an unresolvable circular reference?

Edit:

The problem seems to be caused by WebSecurityConfigurerAdapter inheritance. Some beans are instanciated by this class and create conflict with the dedicated datasource I try to configure for the "security" part of my spring-boot app. I'm still searching...

Edit 2:

If anyboby's got a git URL to a working sample example...



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source