khateeb
khateeb

Reputation: 5469

How to configure Spring for LDAP and JDBC?

In my web application, I have to use Spring Security and get the user's authentication details using LDAP and the user's authorization details using JDBC. The user submits a form and I get the username and password from it.

  1. How Do I get the username and password in my WebSecurityConfig file?
  2. How do I configure the authorization and authentication?

My WebSecurityConfig:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().formLogin()
        .loginPage("/").permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.ldapAuthentication().userDnPatterns("uid={0},ou=people")
                .groupSearchBase("ou=groups").contextSource(contextSource());
    }

    @Bean
    public DefaultSpringSecurityContextSource contextSource() {
        DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(
                "ldap://mjkoldc-03.red.com");
        contextSource.setUserDn("mj\\" + email);
        contextSource.setPassword(password);
        contextSource.setReferral("follow");
        contextSource.afterPropertiesSet();
        return contextSource;

    }
}

Previously I was getting details using LDAPTemplate:

LdapQuery query = query().base("dc=metaljunction,dc=com")
            .attributes("GivenName", "sn", "mail", "MobilePhone")
            .where("ObjectClass").is("user").and("SamAccountName")
            .is(email);

Upvotes: 1

Views: 1467

Answers (1)

alekz
alekz

Reputation: 116

If you what to authentificate agains LDAP and Autorize (get user roles from JDBC) you should implement LdapAuthoritiesPopulator.

public class CustomAuthoritiesPopulator implements LdapAuthoritiesPopulator {

    @Override
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
        Collection<GrantedAuthority> gas = new HashSet<GrantedAuthority>();
        gas.add(new SimpleGrantedAuthority("ADMIN"));
        return gas;
    }
}

and add it to your SecurityConfig

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth        
            .ldapAuthentication()
                .ldapAuthoritiesPopulator(new CustomAuthoritiesPopulator())
                .userSearchFilter("yourfilter")             
            .contextSource(contextSource());    
    }
}

Like this all users authentificated via LDAP will automatically get "ROLE_ADMIN".

Upvotes: 2

Related Questions