如何为LDAP和JDBC配置Spring?

时间:2015-02-11 11:52:26

标签: spring spring-mvc spring-security ldap spring-ldap

在我的Web应用程序中,我必须使用Spring Security并使用LDAP获取用户的身份验证详细信息,并使用JDBC获取用户的授权详细信息。用户提交表单,我从中获取用户名和密码。

  1. 如何在WebSecurityConfig文件中获取用户名和密码?
  2. 如何配置授权和身份验证?
  3. 我的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;
    
        }
    }
    

    以前我使用LDAPTemplate获取详细信息:

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

1 个答案:

答案 0 :(得分:1)

如果你要再次验证LDAP和Autorize(从JDBC获取用户角色),你应该实现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;
    }
}

并将其添加到您的SecurityConfig

public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

像这样通过LDAP验证的所有用户都将自动获得&#34; ROLE_ADMIN&#34;。