Search code examples
rustldapldap3

Rust LDAP with auth


How do I connect to ldap using Rust?

All I could find from the online docs was this:

use ldap3::result::Result;
use ldap3::{LdapConn, Scope, SearchEntry};

fn main() -> Result<()> {
    let mut ldap = LdapConn::new("ldap://localhost:2389")?;
    let (rs, _res) = ldap
        .search(
            "ou=Places,dc=example,dc=org",
            Scope::Subtree,
            "(&(objectClass=locality)(l=ma*))",
            vec!["l"],
        )?
        .success()?;
    for entry in rs {
        println!("{:?}", SearchEntry::construct(entry));
    }
    Ok(ldap.unbind()?)
}

I'm looking for something like python's ldap3


Solution

  • After defining the LdapConn, you need to bind. You have to use distinguished name or email in the bind.

        let result = ldap
            .simple_bind("[email protected]", "password")
            .unwrap()
            .success();
        if result.is_err() {
            println!("This failed")
        } else {
            println!("IT WORKED!")
        }
    
    

    A more practical application:

       assert!(ldap
            .simple_bind("[email protected]", "password")
            .unwrap()
            .success()
            .is_ok());
    

    If you need more options like python's ldap3 you can use LdapConnSettings to specify some of the settings like tls

        let mut ldap: LdapConn = LdapConn::with_settings(
            LdapConnSettings::new()
                .set_no_tls_verify(true)
                .set_starttls(true),
            "ldap://localhost:2389"
        )
        .unwrap();