Spring security Ldap get username password from a encoded cookie for Authentication

Viewed 1052

Currently I've written a Spring Ldap authentication and authorization module with http basic login but now I need to get the username and password from a cookie in request and bind them to ldap for authentication.

Below is my websecurity config class

@Configuration
@EnableWebSecurity
public class LdapSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomLdapAuthoritiesPopulator customLdapAuthoritiesPopulator;

    @Value("${ldap.config.url:ldap://192.168.1.50:389}")
    private String LDAP_URL;

    @Value("${ldap.config.managerdn:uid=admin,cn=users,cn=accounts,dc=example,dc=test}")
    private String MANAGER_DN;

    @Value("${ldap.config.managerpwd:admin123}")
    private String MANAGER_PWD;

    @Value("${ldap.config.basedn:cn=users,cn=accounts,dc=example,dc=test}")
    private String SEARCH_BASE;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity.httpBasic().
        and().authorizeRequests().
                anyRequest().permitAll().
                and().
                csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
            .ldapAuthentication().contextSource().url(LDAP_URL)
            .managerDn(MANAGER_DN)
             .managerPassword(MANAGER_PWD)
                .and()
                    .userSearchBase(SEARCH_BASE)
                    .userSearchFilter("uid={0}")
                    .ldapAuthoritiesPopulator(customLdapAuthoritiesPopulator);            
    }

}

Below is my CustomLdapAuthoritiesPopulator class

@Component
public class CustomLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {


    public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {

        String[] groups = userData.getStringAttributes("memberof");

        List<String> wordList = Arrays.asList(groups);       

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        for (String string : wordList) {

            if(string.toLowerCase().contains("cn=permissions")){
                String parts[] = string.split(",");
                String autho[]=parts[0].split("cn=");
                System.out.println(autho[1]);   
                authorities.add(new SimpleGrantedAuthority(autho[1]));
            }

        }

        return authorities;
    } 

}

Thanks in advance

1 Answers
Related