0

I have multiproject Spring application. Project A - responsible for LDAP authentication Project B - responsible for Database authentication Project MAIN - can use both of them or one of them. If we use only Project A - we have LDAP auth If we use only Project B - we have JDBC auth If we use both of them - first goes LDAP auth, if it failures, then goes JDBC auth. And if Project B is included, it adds some filters

Project MAIN does not have @Configuration file, but Projects A and B has it.

Project A @Configuration

@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

/**адрес сервера LDAP*/
@Value("${ldap.server}")
private String ldapServer;

/**номер порта LDAP сервера*/
@Value("${ldap.port}")
private int ldapPort;

/**домен для LDAP*/
@Value("${ldap.suffix}")
private String suffix;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(adAuthProvider());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic()
            .and()
            .authorizeRequests().antMatchers("/**").authenticated()
            .and()
            .csrf().disable();
}

/**провайдер для аутентификации через LDAP*/
@Bean
public ActiveDirectoryLdapAuthenticationProvider adAuthProvider() {

    String ldapUrl = String.format("ldap://%s:%s", ldapServer, ldapPort);

    ActiveDirectoryLdapAuthenticationProvider adAuthProvider = new 
  ActiveDirectoryLdapAuthenticationProvider(suffix, ldapUrl);
    adAuthProvider.setConvertSubErrorCodesToExceptions(true);
    adAuthProvider.setUseAuthenticationRequestCredentials(true);
    return adAuthProvider;
}

}

and Project B Configuration file.

@Configuration
@EnableWebSecurity
public class ECommonConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(jdbcAuthProvider());    
}

@Override
protected void configure(HttpSecurity http) throws Exception {
 http.httpBasic()
            .and()
            .authorizeRequests().antMatchers("/**").authenticated()
            .and()
            .csrf().disable();
    http.addFilterAt(ldapAuthenticationFilter(), LDAPAuthenticationFilter.class);
    http.authorizeRequests().antMatchers("/**").access("@requestAuthorization.checkRequestPermissions(authentication, request)");
}

/**провайдер для аутентификации через базу данных*/
@Bean
public DaoAuthenticationProvider jdbcAuthProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService);
    authProvider.setPasswordEncoder(passwordEncoder());
    return authProvider;
}

/**бин для шифрования паролей*/
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

/**бин для фильтра проверки наличия LDAP-пользователя в базе данных*/
@Bean
public LDAPAuthenticationFilter ldapAuthenticationFilter() throws Exception {
    return new LDAPAuthenticationFilter(authenticationManager());
}

@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManager();
}

/**бин для инициализации базы данных по умолчанию - описание параметров подключения к БД в файле application.yml*/
@Bean
public DataSource dataSource() {
    return datasourceConnectionManager().getDataSource("test");
}

/**бин создания менеджера подключения к нескольким базам данных*/
@Bean
public DatasourceConnectionManager datasourceConnectionManager() {
    return new DatasourceConnectionManager();
}
}

I need these two configurations works together or only one oh them

art
  • 95
  • 1
  • 12
  • Hope maven and spring profiling will work for you http://dolszewski.com/spring/spring-boot-properties-per-maven-profile/ – RAJKUMAR NAGARETHINAM May 06 '19 at 11:56
  • You can use configuration profiles. profile A or profile B or profile ALL and have your configuration accordingly. – Manmay May 06 '19 at 11:59
  • 1
    I dont need profiles, I need to merge two Configurations clases to one. Maybe I need Configuration class in my main project? – art May 06 '19 at 11:59

2 Answers2

0

To combine this 2 ways of authentication you can create a custom authentication provider ( more details here: https://www.baeldung.com/spring-security-authentication-provider )

The implementation of the auth provider would look something like this:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private ActiveDirectoryLdapAuthenticationProvider ldapAuthenticationProvider;
    private DaoAuthenticationProvider daoAuthenticationProvider;

    // env variable to help you choose which auth provider should be enabled
    @Value("${ldap.enabled}")
    private int ldapEnabled;

    // env variable to help you choose which auth provider should be enabled
    @Value("${daoAuth.enabled}")
    private int daoAuthEnabled;

    @Autowired
    public CustomAuthenticationProvider(ActiveDirectoryLdapAuthenticationProvider ldapAuthenticationProvider, DaoAuthenticationProvider daoAuthenticationProvider) {
        this.ldapAuthenticationProvider = ldapAuthenticationProvider;
        this.daoAuthenticationProvider = daoAuthenticationProvider;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication);

        // if both enabled then first try with ldap, if not successful try with dao
        if (ldapEnabled && daoAuthEnabled ) {
          Authentication authenticate = ldapAuthenticationManager.authenticate(authentication);
          if(!authenticate.isAuthenticated()) {
            authenticate = ldapAuthenticationManager.authenticate(authentication);
          }
          return authenticate;
        }

        // if only ldap enabled 
        if(ldapEnabled) {
          return ldapAuthenticationManager.authenticate(authentication);
        }

        // if only dao enabled
        return daoAuthenticationProvider.authenticate(authentication);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
BogdanSucaciu
  • 884
  • 6
  • 13
-1

You can use Spring profiling for this. Just Add @Profile annotation along with name on the configuration class as shown below. Configuration for ProjectA

@Profile("ProjectA")
@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...

And Configuration for ProjectB

@Profile("ProjectB")
@Configuration
@EnableWebSecurity
public class ECommonConfig extends WebSecurityConfigurerAdapter {
...

Then at the time of execution of application you can specify active profile by passing following parameter to java.

#In case of need of only ProjectA then
-Dspring.profiles.active=ProjectA
#In case of need of only ProjectB then
-Dspring.profiles.active=ProjectB
#In case of need of both projects then
-Dspring.profiles.active=ProjectA,ProjectB

Same thing you can define in application.properties file with required profile

spring.profiles.active=ProjectA,ProjectB

This way you can dynamically decide which Project configuration should be included.

  • Not worked for me. Only COnfiguration working with higher order. Second Configuration not working – art May 06 '19 at 12:23