Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created February 5, 2015 16:49
Show Gist options
  • Save bdkosher/acd8e74b3b77f001b819 to your computer and use it in GitHub Desktop.
Save bdkosher/acd8e74b3b77f001b819 to your computer and use it in GitHub Desktop.
Sample script for running queries against Active Directory
@Grab(group='org.springframework.security', module='spring-security-core', version='3.2.5.RELEASE')
@Grab(group='org.springframework.security', module='spring-security-ldap', version='3.2.5.RELEASE')
import groovy.transform.*
import javax.naming.NamingException
import javax.naming.directory.Attribute
import javax.naming.directory.Attributes
import org.springframework.ldap.core.*
import org.springframework.security.ldap.*
def url = 'ldap://host.example.com:389/DC=EXAMPLE,DC=COM'
def user = /CN=Lastname\, Firstname,CN=Users,DC=EXAMPLE,DC=COM/
def pass = 'password'
def values = [1234, 5678, 910]
def template = new SpringSecurityLdapTemplate({ ->
new DefaultSpringSecurityContextSource(url).with {
userDn = user
password = pass
afterPropertiesSet()
delegate // it'd be nice to have a with return the delegate by default, in some respects
}
}())
/* Convenience method */
String val(Attributes atts, String name) {
atts.get(name).get().toString()
}
@TupleConstructor
class User {
String id, username, name, email
@Override
String toString() {
"$id,$username,$email"
}
}
Set<User> users = [] as Set
// could posibly use an IN clause instead of multiple searches
values.each { value ->
template.search('CN=Users', "(extensionAttribute14=$value)", { atts ->
new User(val(atts, 'employeeID'), val(atts, 'sAMAccountName'), val(atts, 'cn'), val(atts, 'mail'))
} as AttributesMapper).each { users << it }
}
users.each { println it }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment