Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

connection to Active directory from Java

  Asked By: Manju    Date: Jun 16    Category: Java    Views: 6556
  

I advice you to use other directories such
as OpenLDAP http://www.openldap.org, netscape
directory, sun directory (if you live in Iran
unfortunatly you cant download them) and so on, I use
openLDAP myself, because it is an open source, so
light and you dont need to install server version of
OS, it works on any platforms(linux, mac ...), also
you can change its structure easilly and many other
benefites. However, if you have to use MS Active
directory(MSAD) for the first step you must install MS
Active directory application mod (ADAM) (because MSAD
has two version 1. ordinary 2. app. mode), after that
you should download JNDI.jar (if you use JDK 1.4 or
later it has this file), also you can use other jar
file like ldapjdk.jar which has written by novel. (I
suggest you to use sun jar file is better)
secondly, you must use JNDI (Java naming directory
Interface)api. it consists of some interface and spi
that you can use it(you can find good info. on
http://java.sun.com/j2se/1.3/docs/api/javax/naming)

I worte a sample code for you, I hope it will be
usefull: (it search correctly)


public class SearchFilter {
public static void main (String[] args) {

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");

env.put(Context.PROVIDER_URL,"ldap://localhost:389/o=tafahom.org");
env.put(Context.SECURITY_PRINCIPAL,
"cn=manager,o=tafahom.org");
env.put(Context.SECURITY_CREDENTIALS,
"XXXXXX");
try {
DirContext ctx = new
InitialDirContext(env);
Name name = new
LdapName("ou=Development");
String filter =
"(|(|(sn=mowla*)(cn=kav*))(l=esfa*))";
SearchControls searchControl = new
SearchControls();
searchControl.setCountLimit(4);

NamingEnumeration answer =
ctx.search(name,filter,searchControl);
while(answer.hasMore()){
SearchResult result =
(SearchResult) answer.next();
System.out.println(">>>" +
result.getNameInNamespace());

PrintAttrsAll.printAttrs(result.getAttributes());
}
ctx.close();

} catch (NamingException e) {
e.printStackTrace(); //To change body
of catch statement use File | Settings | File
Templates.
}
}
}

Share: 

 

4 Answers Found

 
Answer #1    Answered By: Leonard Pierce     Answered On: Jun 16

live  in canada , so I dont have problem to download  this software, But we have already installed MS active  Directory and we are using that.

1- why do I need to install  this software? what are benefits of switching to penLDAP ?

2- I could access to AD and I could list users in each department . but I dont know how to fetch their emails? I am getting errors when I use any string  filter .It means I am just able to list not search(doesnt make sense to me either)

3- How can I know which kind of microsoft active directory  I am using?

 
Answer #2    Answered By: Elisabeth Bell     Answered On: Jun 16

I'm so happy because my info. was usefull. you asked
me 3 questions and I try  to answer  them respectively.

1. as I mentioned in my prevous mail, openLDAP is an
open source, so you shouldnt pay. another benefit is,
it is a lightweight directory, it needs almost 20MB
disk and over 3MB memory space. In addition, it
installs easily. Furthermore, you can add and modify
its schemas easitly.also, backup and recovery is fast
and easy(slapcat).the most important point is, it
works on every platforms(windows, linux,...) and it
can work on home edition version  of windows. general
speaking it is light, fast, free and secure. However,
it doesnt support RDN(Relative Distingush Name)and in
comparision with AD, ACL configuration is not so easy
in openLDAP.

2. I dont understand it exactly, could you plz, give
me more details about it. you can conn. to AC with
JNDI or via its browser? and can you list your users
by using JNDI? if you remember, I wrote in my last
mail a search  class(SearchFilter), it fetchs all of
info.; please mail me your codes.
may be below link can help you:
forum.java.sun.com/thread.jspa

3. I'm not sure because I'm not expert in MSAC and I
can help you a little. in AC you can see windows
authenticate window, but ADAM(App. mode) dosent have
this one. you can find  good info. on this site:
www.microsoft.com/windowsserver2003/
technologies/directory/activedirectory

- unfortunatly, I couldnt import data from AD to
openLDAP, owing to deferences of their schemas.if
anyone know anythings about it plz tell me.

 
Answer #3    Answered By: Midissia Lopez     Answered On: Jun 16

I should say about filtering in directories  briefly,
they use Polish(prefix) algorithm to filter  their
data. for example if you want to find  a person with
this DN: cn=button, o=x.org
(it is a serialazable object)or ou=developers, o=x.org
you have to write:

...

Name compoundName = parser.parse("");
String filter = "(|(ou=dev*)(cn=button))";

 
Answer #4    Answered By: Sebastien Anderson     Answered On: Jun 16

You don't add groups to users, you add users (or groups, or computers ..) to groups !

One of the attributes of a user object is "memberOf" and conversely one of the attributes of a group is "member"

memberOf is not a "real" attribute per se, meaning that it is read only, it contains "links" to groups and that it is constructed from all the groups that the user is a member of in that domain.

The reason why it has links to groups is to ensure referential integrity Eg. if you delete, rename or move a user, the group's membership is correctly maintained.

it is read-only, and if you attempt to modify it's values you wil get a ldap  Error of the form:
javax.naming.OperationNotSupportedException: [LDAP: error code  53 - 0000209A: SvcErr: DSID-031A0DD1, problem 5003 (WILL_NOT_PERFORM),data 0];

One other phenonema is that the user's membership only reflects the groups that are known on the domain controller that is being queried. In a multi-domain or multi-forest environment, a domain controller will only have knowledge of groups in it's own domain.

If the domain controller is a Global Catalog, it will have knowledge of all groups in the forest so it will reflect the list of groups in the forest that a user is a member of.

This is a slight simplification, with Windows Server 2003, branch office scenarios enable caching of group memberships without the need for a global catalog. (Me thinks a description of the Global Catalog is a future forum topic).

Therefore viewing a user's memberOf attribute may not reveal the full list of groups that a user is a member of. In addition, memberOf does not contain the user's Primary Group membership, nor does it reflect groups in other forests that the user may belong to.

The following code demonstrates viewing a user's memberOf attribute



import java.util.Hashtable;
import javax.naming.*;
import javax.naming.ldap.*;
import javax.naming.directory.*;

public class  memberof {
 public  static void  main (String[] args) {

Hashtable env  = new Hashtable();
String adminName = "CN=Administrator,CN=Users,DC=ANTIPODES,DC=COM";
String adminPassword = "XXXXXXX";
String ldapURL = "ldap://mydc.antipodes.com:389";
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
//set security credentials, note using simple cleartext authentication
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,adminName);
env.put(Context.SECURITY_CREDENTIALS,adminPassword);

//connect to my domain controller
env.put(Context.PROVIDER_URL,ldapURL);

 try  {

//Create the initial directory  context
LdapContext ctx = new InitialLdapContext(env,null);

//Create the search  controls
SearchControls searchCtls = new SearchControls();

//Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

//specify the LDAP search filter  
String searchFilter = "(&(objectClass=user)(CN=Andrew Anderson))";

//Specify the Base for the search
String searchBase = "DC=antipodes,DC=com";

//initialize counter to total the group members
int totalResults = 0;

//Specify the attributes to return
String returnedAtts[]={"memberOf"};
searchCtls.setReturningAttributes(returnedAtts);

//Search for objects using the filter
NamingEnumeration answer  = ctx.search(searchBase, searchFilter, searchCtls);

//Loop through the search results
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult)answer.next();

System.out.println(">>>" + sr.getName());

//Print out the groups

Attributes attrs = sr.getAttributes();
if (attrs != null) {

try {
for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) {
Attribute attr = (Attribute)ae.next();
System.out.println("Attribute: " + attr.getID());
for (NamingEnumeration e = attr.getAll();e.hasMore();totalResults++) {

System.out.println(" " + totalResults + ". " + e.next());
}

}

}
 catch  (NamingException e) {
System.err.println("Problem listing membership: " + e);
}

}
}

System.out.println("Total groups: " + totalResults);
ctx.close();

}

catch (NamingException e) {
System.err.println("Problem searching directory: " + e);
}
}
}

An alternative is to use another constructed attribute, tokenGroups. It will return the list of Security Identifiers (SID) that are in the user's security token.

There are a few things to be aware of when using tokenGroups:
1. The SID's are in binary format and would need to be formatted into the "S-1-5-aa-bb-cc-dd" format to be human readable
2. You would then need to do searches using the SID to find  the distingusihed names of the groups that tehy map to.
3. The search base must be OBJECT_SCOPE
Eg.

//Specify the search scope
searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

//specify the LDAP search filter
String searchFilter = "(objectClass=user)";

//Specify the Base for the search
String searchBase = "CN=Andrew Anderson,OU=Research,DC=antipodes,DC=com";

 
Didn't find what you were looking for? Find more on connection to Active directory from Java Or get search suggestion and latest updates.




Tagged: