Giriş
Şu satırı dahil
ederiz.
import javax.naming.directory.InitialDirContext;
Bu sınıf LDAP üzerinde çalışabilmek için gerekli. Bir çeşit soket bağlantısı gibi düşünülebilir.
constructor - simple
Bind işlemi gerçekleşince, LDAP sunucusuna bağlanmak için kullanılan kullanıcı ismi ve şifrenin doğrulanması da yapılmış
olur. Bağlantı gerçekleşemez ise veya kullanıcı doğrulanamazsa
AuthenticationNotSupportedException,
AuthenticationException,
NamingException gibi bir exception
atılır.
Örnek
Şöyle
yaparız.
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "mysecret");
DirContext ctx = new InitialDirContext (env);
Bu kod ile şu
aynıdır.
String ldapContext = String.format("ldap://%s", ldapHostname);
Hashtable<String, String> ldapUserProperties = new Hashtable<String, String>();
ldapUserProperties.put(Context.SECURITY_PRINCIPAL, ldapUsername);
ldapUserProperties.put(Context.SECURITY_CREDENTIALS, ldapPassword);
try {
DirContext directoryContext = LdapCtxFactory.getLdapCtxInstance(ldapContext,
ldapUserProperties);
authenticationGranted = true;
} catch (NamingException e) {
...
}
Örnek
Şöyle
yaparız
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:10389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
env.put(Context.SECURITY_CREDENTIALS, "secret");
DirContext ctx = new InitialDirContext(env);
Şu parametreleri de
kullanabilirdik.
Context.SECURITY_PRINCIPAL = "cn=Directory Manager,dc=corio";
Context.SECURITY_CREDENTIALS = "secret";
constructor - SASL
SASL ise
Simle Authentication and Security Layer anlamına geliyor. Açıklaması
şöyle:
A BIND request has two forms: simple and SASL. Simple uses a distinguished name and a password, SASL uses one of a choice of mechanisms, for example, PLAIN, LOGIN, CRAM-MD5, DIGEST-MD5, GSSAPI, and EXTERNAL - all of which except for GSSAPI and EXTERNAL are too weak to use in production scenarios or mission-critical areas.
close metodu
Şöyle
yaparız.
ctx.close();
createSubcontext metodu Örnek - Yeni Kullanıcı Eklemek
public void addUser() {
Attributes attributes = new BasicAttributes();
Attribute attribute = new BasicAttribute("objectClass");
//adding values for objectClass attribute
attribute.add("inetOrgPerson");
attribute.add("person");
attribute.add("organizationalPerson");
attribute.add("top");
attributes.put(attribute);
//adding other attribute details
attributes.put("sn", "Jaeger");
attributes.put("cn", "Eren Jaeger");
attributes.put("givenName", "Eren Jaeger" );
attributes.put("uid", "Eren");
attributes.put("userPassword", "password");
attributes.put("mail", "erenye@hotmail.com");
try {
//add the path where the object needs to be created (uid vs cn)
//and the attributes of the object to be added.
connection.createSubcontext("uid=Erenye,ou=users,ou=system", attributes);
System.out.println("User Added Successfully");
} catch (NamingException e) {
System.out.println("error when trying to create the context");
}
}
destroySubcontext metoduÖrnek - Kullanıcı Silmek
public void deleteUser(String uid) {
try {
connection.destroySubcontext("uid=" + uid + ",ou=users,ou=system");
System.out.println("User " + uid + " deleted successfully");
} catch (NamingException e) {
System.out.println("error when trying to create the context");
}
}
getEnvironment metodu
Şöyle
yaparız.
System.out.println (ctx.getEnvironment());
modifyAttributes metoduÖrnek - Adding a User to a Group
Şöyle
yaparızpublic void addUserToGroup(String username, String groupname) {
ModificationItem[] mods = new ModificationItem[1];
//uniqueMember - uid=username,ou=user,ou=system
//The attribute to be added to the group
Attribute attribute = new BasicAttribute("uniqueMember", "uid=" +
username + ",ou=user,ou=system");
mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attribute);
try {
//groupname is the group that needs to be modified.
connection.modifyAttributes("cn=" + groupname + ",ou=groups,ou=system", mods);
System.out.println(username + " Successfully added to " + groupname + " group");
} catch (NamingException e) {
System.out.println("error when trying to create the context");
}
}
search metodu - name + filter + SearchControls
NamingEnumeration döner.
Örnek
Şöyle
yaparız.
SearchControls ctl = new SearchControls();
ctl.setSearchScope (SearchControls.SUBTREE_SCOPE);
NamingEnumeration results = ctx.search ("dc=corio","uid=swethagm",ctl);
Örnek
Şöyle yaparız.// Perform search in the entire subtree.
SearchControls ctl = new SearchControls();
ctl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration results = ctx.search ("", null, ctl);
Örnekpublic void getAllUsers() throws NamingException {
String searchFilter = "(objectClass=Person)";
String[] requiredAttributes = {"sn", "cn"};
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setReturningAttributes(requiredAttributes);
NamingEnumeration users = connection.search("ou=users, ou=system",
searchFilter, controls);
SearchResult result = null;
while (users.hasMore()) {
result = (SearchResult) users.next();
Attributes attr = result.getAttributes();
System.out.println(attr.get("cn") + "," + attr.get("sn"));
}
}
Örnekpublic void searchUser(String uid) throws NamingException {
String searchFilter = "(&(objectClass=inetOrgPerson)(uid=" + uid + "))";
String[] requiredAttributes = {"sn", "cn"};
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setReturningAttributes(requiredAttributes);
NamingEnumeration users = connection.search("ou=users, ou=system",
searchFilter, controls);
SearchResult result = null;
while (users.hasMore()) {
result = (SearchResult) users.next();
Attributes attr = result.getAttributes();
System.out.println(attr.get("cn") + "," + attr.get("sn"));
}
}