Printing uid using JNDI & LDAP

Hi all,
can any one give me the code to print uid(userid).
thanks..

here is the my code.::
can you help, i an not able print the user id..
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class LDAP {
* @param args
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, "myhost");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(LdapContext.CONTROL_FACTORIES, "com.sun.jndi.ldap.ControlFactory");
String searchFilter = "(&(objectClass=group)(CN=xyz))";
String searchBase="DC=abc.net";
try {
DirContext ctx = new InitialLdapContext(env, null);
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctls.setReturningAttributes(returnedAttrs);
int total=0;
NamingEnumeration answer = ctx.search(searchBase, searchFilter, ctls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult)answer.next();
if (sr != null) {
Attributes attrs = sr.getAttributes();
if (attrs != null) {
try {
for (NamingEnumeration ne = attrs.getAll(); ne.hasMore();) {
Attribute attr = (Attribute)ne.next();
System.out.println ("Attribute: " + attr.getID());
for (NamingEnumeration e = attr.getAll(); e.hasMore();total++) {
System.out.println (" " + total + ". " + e.next().toString());
} catch (NamingException n) {
n.printStackTrace();
System.out.println ("Total Members: " + total);
ctx.close();
} catch (NamingException ne) {
ne.printStackTrace();
}

Similar Messages

  • Creating a simple network services directory using JNDI/LDAP

    I want to create a simple directory of all the local network services.
    For example:
    o=NetworkServices
      ou=Databases
        cn=FooDB
          attributes >> ipAddress, networkAddress, typeService, typeHost, description
        cn=BarDB
       ou=Authentications
        cn=FooAuth
        cn=BarAuth
       ou=Communities
        cn=FooComm
        cn=BarCommIs there a simple schema (DIT) that can service this need?
    I looked a nis.schema, http://usermap.cvut.cz/ldap/nis.schema, and it appears to be overkill for my needs, plus I do not understand all the attributes it defines.
    Thanks

    hi guys,
    I don't know maybe the way i structure the question is wrong.
    The link to the form is going to be on the intranet, the moment anybody is able to logon to his system with his nt userid , he clicks on the form and this form displays his details. i have a database that contain all the staff details but how do i get his nt userid that i'll use to search the database.
    A dot net programmer has been able to get the userid and if by monday i can't get the userid i'll have to go and learn dot net or leave the company.
    Greatest javites, any hint will be appreciated.
    Best Regards

  • How to get the naming attribute of an LDAP using JNDI.?

    Hi,
    How do we fetch the naming attribute of a LDAP using JNDI. Is this possible using JNDI..?
    By default, every LDAP has been set with a naming attribute such as 'uid' or 'cn'. This could be changed according to business needs.
    How to determine this using JNDI.
    Regards,
    Barani

    Are you trying to call the portlet Customization form directly from the browser?

  • Connecting to LDAP using JNDI

    I am trying to connect to LDAP to check an entry.
    Following is the servlet code I am using.
    /* @author
    This class is establish to connect the LDAP user directory and get the user attributes
    (SSO_USERID, USER_ID, USER_NAME and USER_MAIL) from the LDAP User directory. */
    import java.io.*;
    import java.util.Enumeration;
    import java.util.*;
    import javax.naming.*;
    import javax.naming.directory.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.lang.*;
    public class LDAPSearch extends HttpServlet
              //public static String MY_FILTER1 = "";
              public static String MY_FILTER2 = "";
              public static String INITCTX="com.sun.jndi.ldap.LdapCtxFactory";
              public static String MY_HOST="ldap://3.245.97.5:389";
              public static String MY_SEARCHBASE="o=ge.com";
              public void doGet (HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException
                   doPost(request,response);
              public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
                        PrintWriter out=response.getWriter();
                        try
                             HttpSession session = request.getSession(true);
                             String str_user=(String)request.getParameter("txtSearch");
                             //out.println(str_user);
                             String ssoid = request.getParameter("ssoid");
                             //String str_parname = (String)request.getParameter("selNames");
                             System.out.println("str_user"+str_user);
                             String firstName="";
                             String lastName="";
                             String str_complete = "";
                             //char data[]={str_user,',');
                             StringTokenizer st=new StringTokenizer(str_user,",");
                             int stCount = st.countTokens();
                             if(stCount == 1)
                                  firstName = st.nextToken();
                                  System.out.println("firstName "+firstName);
                             else
                                  while(st.hasMoreTokens())
                                       lastName=st.nextToken();
                                       firstName=st.nextToken();
                                       //out.println("firstName "+firstName);
                                       //out.println("lastName "+lastName);
                        if(ssoid == null)
                             if(stCount == 1)
                                       MY_FILTER2 = "(givenName="+firstName+")";
                                       System.out.println("MY_FILTER2"+MY_FILTER2);
                                  else
                                  MY_FILTER2 = "(&(givenName="+firstName+")(sn="+lastName+"))";
                                  //out.println("MY_FILTER2"+MY_FILTER2);
                             else
                                  MY_FILTER2 = "(cn="+ssoid+")";
                             out.println("<html>");
                             out.println("<head><title>SSO User lookup / Search</title></head>");
                             out.println("<script language=\"javascript\">");
                             out.println("function back(){");
                             out.println("document.frmLDAPSearch.ssoid.value = document.frmLDAPSearch.selNames[document.frmLDAPSearch.selNames.selectedIndex].value;");
                             out.println("document.frmLDAPSearch.target='ERPUser';");
                             out.println("document.frmLDAPSearch.submit();");
                             out.println("window.close();");
                             out.println("}");
                             out.println("</script>");
                             out.println("<BODY BGCOLOR='#FFFFFF'><table border='0' align = 'center' width = '100%' >");
                             out.println("<form name=\"frmLDAPSearch\" method=\"get\" action='/servlet/LDAPSearch'>");
                             String str_ssoid = "";
                             String str_uid="";
                             String str_mailid = "";
                             String str_name = "";
                             String last = "";
                             String str_fullname = "";
                             //out.println("Origninal name "+str_parname);
                             Hashtable env=new Hashtable();
                             env.put(Context.INITIAL_CONTEXT_FACTORY,INITCTX);
                             env.put(Context.PROVIDER_URL,MY_HOST);
                             DirContext ctx=new InitialDirContext(env);
                             SearchControls constraints=new SearchControls();
                             constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
                             Vector vOut = new Vector();
                             NamingEnumeration results=ctx.search(MY_SEARCHBASE,MY_FILTER2,constraints);
                             while(results !=null && results.hasMore())
                                       SearchResult sr=(SearchResult)results.next();
                                       String dn=sr.getName() +"," +MY_SEARCHBASE;
                                       Attributes attrs=sr.getAttributes();
                                       for(NamingEnumeration ne=attrs.getAll();ne.hasMoreElements();)
                                            Attribute attr=(Attribute)ne.next();
                                            String attrID=attr.getID();
                                            if(attrID.equals("mail"))
                                                 Enumeration vals=attr.getAll();
                                                 out.println("<font color=\"red\">");
                                                 str_mailid = (String)vals.nextElement();
                                            if(attrID.equals("gessouid"))
                                                 Enumeration vals=attr.getAll();
                                                 out.println("<font color=\"red\">");
                                                 str_ssoid = (String)vals.nextElement();
                                            if(attrID.equals("uid"))
                                                 Enumeration vals=attr.getAll();
                                                 out.println("<font color=\"red\">");
                                                 str_uid = (String)vals.nextElement();
                                            if(attrID.equals("givenname"))
                                                 Enumeration vals=attr.getAll();
                                                 out.println("<font color=\"red\">");
                                                 str_name = (String)vals.nextElement();
                                            for(Enumeration vals=attr.getAll();vals.hasMoreElements();)
                                                 vals.nextElement();
                                            if(attrID.equals("sn"))
                                                 Enumeration vals=attr.getAll();
                                                 out.println("<font color=\"green\">");
                                                 last = (String)vals.nextElement();
                                            if(attrID.equals("cn"))
                                                 Enumeration vals=attr.getAll();
                                                 out.println("<font color=\"green\">");
                                                 str_complete = (String)vals.nextElement();
                                                 System.out.println("str_complete "+str_complete);
                                            //if(lastName.equalsIgnoreCase(last) || (stCount == 1))
                                                 if(attrID.equals("cn"))
                                                      int i=0;
                                                      Enumeration vals=attr.getAll();
                                                      out.println("<font color=\"red\">");
                                                      str_fullname = (String)vals.nextElement();
                                                      vOut.addElement(new String(str_fullname));
    //                                   } //END OF IF LASTNAME EQUALS
                                  }//END OF FOR LOOP
                             }//END OF WHILE"#FF00FF"
                                       out.println("<form><body bgcolor='#00FFFF' >");
                                       out.println("<div align=\"CENTER\" >");
                                       out.println("<input type=hidden name=txtSearch value='"+str_user+"'>");
                                       System.out.println("LDAP SEARCH: txtSearch="+str_user);
                                       out.println("<input type=hidden name=ssoid value=''>");
                                       String multiple=request.getParameter("multiple");
                                       if (multiple!=null)
                                       if (multiple.equalsIgnoreCase("true"))
                                                 out.println("<br>");
                                                 out.println("<table align=\"center\" >");
                                                 out.println("<tr><td align=\"center\"><select name='selNames' size=3>");
                                                 out.println("<option value='"+vOut.elementAt(0).toString()+"' selected>");
                                                 out.println(vOut.elementAt(0).toString());
                                                 out.println("</option>");
                                                 for(int i=1;i<vOut.size();i++)
                                                      out.println("<option value='"+vOut.elementAt(i).toString()+"'>");
                                                      out.println(vOut.elementAt(i).toString());
                                                      out.println("</option>");
                                                      System.out.println("i"+i);
                                                 out.println("</select><td></tr>");
                                                 out.println("<tr bgcolor='#00638C'><td align=\"center\"><input type=\"button\" value=\"populate\" onclick=\"back();\"></td>");
                                                 out.println("</td></tr></table>");
                                                 out.println("</div></body</form>");
                                       else{
                                       if(vOut.size()==1)
                                            session.putValue("SSOID",str_ssoid);
                                            session.putValue("USERID",str_uid);
                                            session.putValue("EMAIL",str_mailid);
                                            session.putValue("NAME",str_complete);
                                            response.sendRedirect("/servlet/Protected/InvtAddUser?txtSearch="+str_user);
                                       else if(vOut.size()==0)
                                            out.println("<SCRIPT SRC='/InvTrack/InvTrack.js'>");
                                            out.println("</SCRIPT>");
                                            out.println("<BODY BGCOLOR='#FFFFFF' onUnload='winLogout()' >");
                                            out.println("<table border='0' cellpadding='0' cellspacing='0' width='100%' >");
                                            out.println("<tr><td><img src='/ge.gif'alt='GE Medical Systems'></td>");
                                            out.println("<td><img src='/gr_toprighthd.jpg' alt='GE Medical Systems'></td></tr></table>");
                                            out.println("<BR><BR><BR>");
                                            out.println("<P ALIGN='CENTER'><FONT COLOR='#333399' SIZE='4'><B><FONT FACE='ARIAL, HELVETICA, SANS-SERIF'> <FONT COLOR='#800000'>Sorry!</FONT></FONT></B></FONT></p>");
                                            out.println("<P ALIGN='CENTER'><FONT COLOR='#333399' SIZE='4'><FONT FACE='ARIAL, HELVETICA, SANS-SERIF'> either you have typed incorrectly <br>or user has not registered a GEMS Intranet Single Sign On Userid </FONT></p>");
                                            out.println("<P ALIGN='CENTER'><FONT COLOR='#333399' SIZE='4'><FONT FACE='ARIAL, HELVETICA, SANS-SERIF'><A HREF=\"Javascript:history.back();\">Back</A></FONT></P>");
                                            out.println("</body>");
                                  else
                                            response.sendRedirect("/servlet/Protected/InvtAddUser?multiple=true&txtSearch="+str_user);
                                       out.println("</form></body></html>");
                        catch(Exception e)
                             out.println(e.toString());
    I am getting the followung exception::
    [03/Feb/2002:16:46:29] failure ( 481): Internal error: exception thrown from the servlet service function (uri=/servlet/LDAPSearch): java.lang.NoClassDefFoundError: com/sun/jndi/toolkit/ctx/ComponentDirContext, Stack: java.lang.NoClassDefFoundError: com/sun/jndi/toolkit/ctx/ComponentDirContext
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java, Compiled Code)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java, Compiled Code)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java, Compiled Code)
         at java.net.URLClassLoader.access$1(URLClassLoader.java, Compiled Code)
         at java.net.URLClassLoader$1.run(URLClassLoader.java, Compiled Code)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java, Compiled Code)
         at java.lang.ClassLoader.loadClass(ClassLoader.java, Compiled Code)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java, Compiled Code)
         at java.lang.ClassLoader.loadClass(ClassLoader.java, Compiled Code)
         at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:77)
         at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:671)
         at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:242)
         at javax.naming.InitialContext.init(InitialContext.java:218)
         at javax.naming.InitialContext.<init>(InitialContext.java:194)
         at javax.naming.directory.InitialDirContext.<init>(InitialDirContext.java:87)
         at LDAPSearch.doPost(LDAPSearch.java, Compiled Code)
         at LDAPSearch.doGet(LDAPSearch.java:34)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:701)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:826)
         at com.netscape.server.http.servlet.NSServletRunner.Service(NSServletRunner.java:462)
    I have included ldap.jar and jndi.jar in the CLASSPATH for IPlanetWebServer that I am using.
    Please get back.

    java.lang.NoClassDefFoundError: com/sun/jndi/toolkit/ctx/ComponentDirContext
    Seems pretty straight forward to me. That class isn't there, and it wants it. Check all your classpaths to verify that class is in them. I bet it's not. Also, a side note. You see where it says "compiled code" in the stack trace instead of a line number. You can force the VM to interpret to give you a line number by setting your JAVA_COMPILER variable to "none" Or depending on the version of the VM you are using you can supply the -Xint switch which forces interpretation.

  • Sample code to connect LDAP server using jndi

    Hi,
    can any one help me with sample code to connect LDAP server using jndi,
    like i want to make use of Ldap server for serching Active directoty.
    Thanks in advance,
    Regards
    Muthu

    You can set ldap_auth=none for anonymous user.
    User/password is mandatory otherwise. Please refer to http://docs.oracle.com/cd/E21764_01/integrate.1111/e12644/appendix_ldap_driver.htm#CHDHCABH
    Thansk,

  • Setting up LDAP Server to lookup Connection Factories using JNDI

    Can someone let me know how to setup LDAP server within 10G to lookup connection factories using JNDI?
    I read through the Advanced Queuing User Guide and Reference document where this is mentioned and it says use the Database Configuration Assistant to do this but I could not find how.
    When I install 10G is LDAP server automatically setup? How do I get to it?
    Thanks

    That is correct. I was indeed able to use the app server (10g) to give the LDAP user permission to access the objects, then used sql commands to register the objects inside the LDAP.
    However, I am finding NOTHING about actually creating a unique connection factory that can be registered in the LDAP. I find reference to registering Queues/Topics/Factories inside the LDAP, but nothing about actually creating the factories.
    In fact, here
    http://download.oracle.com/docs/cd/B28359_01/server.111/b28420/aq_envir.htm#sthref409
    it's listed that you cannot use sql to create a connectionfactory... not to mention the create java commands for factories look strikingly similar to the queue/topic GET commands, and not the create commands. You can add an alias for that factory using sql, but can't actually create the factory using sql... ???

  • Please Help.  How can you monitor a directory using jndi connection to a ldap server?

    How can you monitor a directory using jndi connection to a ldap server? I
    want the ldap server to monitor the content change in a file system
    directory on another computer on the network. Can someone please help.
    Thanks
    Fred

    Hi,
    Why do you want to use LDAP for Hard disk monitoring..???
    U can do this by creating a MD5 checksum for all the files existing in some
    perticular
    directory and every hour or any configurable period u can recalculate the
    checksum
    to find out the change in the content.
    I guess all u need is to get the code for "updatedb" utility of Linux and
    instrument it for ur needs..
    Hope it helps...
    -aseem
    mr wrote:
    How can you monitor a directory using jndi connection to a ldap server? I
    want the ldap server to monitor the content change in a file system
    directory on another computer on the network. Can someone please help.
    Thanks
    Fred

  • Using JNDI to connect LDAP directory : pb of reconnection

    Hi everybody !
    I really need our help.
    I work with java servlets and i try to connect a LDAP directory with JNDI.
    When i launch my application, and when LDAP server is ready, connection is done, i get data from ldap, everything is ok.
    But when ldap server fails down, and startup, (my application doesn't stop), i can't connect again to ldap (ldap connext is not null). I get an error "Connection reset by peer, socket write error".
    I can't connect, even if i put my context null, and build another context, to get ldap data.
    Maybe its a problem of servlet programmation, or JNDI use, i don't know.
    Any ideas ?? Thanks you so much for your help !
    Here i give my code, to build ldap context (which is equivalent to a connection to ldap) :
    _env = new Hashtable();
    env.put(Context.INITIALCONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDERURL, "ldap://"+_ldapIPAddress+"/o=netcentrex");
    //securite
    env.put(Context.SECURITYAUTHENTICATION, "simple");
    env.put(Context.SECURITYPRINCIPAL, "cn=admin, o=div");
    env.put(Context.SECURITYCREDENTIALS, "admin");
    try
    ldapCtx = new InitialDirContext(env);
    catch(NamingException e)
    System.out.println("ConnectionLdap : Cannot get directory context for LDAP");

    Sorry, no need to reply !!
    I've found my error (3 days i am searching, and its a stupid null ldap address) !!!

  • Problem in connecting to LDAP using JNDI please HELP ME!!!!!!

    hi
    i am trying to connect to the LDAp using the JNDi
    and i am getting the following error i was unable to solve it
    here i am posting my sample slapd.cof file as well as my source program and the error
    # ldbm database definitions
    database        ldbm
    #suffix         "dc=stooges,dc=org"
    suffix          "o=sgstest"
    rootdn          "cn=sgstestAdmin,o=sgstest"
    rootpw          secret3
    directory       /var/lib/ldap/sgstest
    defaultaccess   read
    schemacheck     off
    lastmod         onand my program source code is
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.naming.NameAlreadyBoundException;
    import javax.naming.directory.*;
    import java.util.*;
    public class test{
            final static String ldapServerName = "localhost";
            final static String rootdn = "cn=SgstestAdmin,o=sgstest";
            final static String rootpass = "secret3";
            final static String rootContext = "o=sgstest";
            public static void main(String[] args) {
                    Properties env = new Properties();
                    env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
                    env.put(Context.SECURITY_AUTHENTICATION,"simple");
                    env.put(Context.PROVIDER_URL,"ldap://"+ldapServerName+"/"+rootContext);
                    env.put(Context.SECURITY_PRINCIPAL,rootdn);
                    env.put(Context.SECURITY_CREDENTIALS,rootpass);
                    try {   // obtain initial directory context using the environment
                            DirContext ctx = new InitialDirContext(env);
                           // now, create the root context, which is just a subcontext
                            // of this initial directory context.
                            Integer i = new Integer( 28420 );
                            System.out.println("Adding " + i + " to directory..." );
                            ctx.bind("cn=myRandomInt",i);
                            i = new Integer( 98765 );
                            System.out.println( "i is now: " + i );
                    } catch (NameAlreadyBoundException nabe) {
                            System.err.println(rootContext + " has already been bound!" );
                    } catch ( Exception e ) {
                            System.err.println( e );
                                                                                                               1,17          Top
    }the error which i am getting is
    Adding 28420 to directory...
    javax.naming.directory.InvalidAttributeIdentifierException:
    [LDAP: error code 17 - javaSerializedData: attribute type undefined]; remaining name 'cn=myRandomInt'any help would be appreciated

    Hi,
    just one question: is your LDAP server configured to support the JAVA object classes and attributes like javaSerializedData? E.g., if you're using openldap, you have to add a line to the slapd.conf configuration file to import the java definitions.

  • Need help in retrieving attributes from LDAP using JNDI

    I am trying to retrieve attributes from LDAP using JNDI, but I'm getting the following error when I try to run my Java program.
    Exception in thread "main" java.lang.NoClassDefFoundError: javax/naming/NamingException
    I have all the jar files in my classpath: j2ee.jar, fscontext.jar and providerutil.jar. The interesting thing is that it gets compiled just fine but gives an error at run-time.
    Could anyone tell me why I'm getting this error? Thanks!
    Here's my code:
    import javax.naming.*;
    import javax.naming.directory.*;
    import java.util.*;
    import java.io.*;
    class Getattr {
    public static void main(String[] args) {     
    // Identify service provider to use     
    Hashtable env = new Hashtable(11);     
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");      
    // user     info
    String userName = "username";     
    String password = "password";          
    // LDAP server specific information     
    String host = "ldaphostname";     
    String port = "portnumber";     
    String basedn = "o=organization,c=country";     
    String userdn = "cn=" + userName + "," + basedn;          
    env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + basedn);     
    env.put(Context.SECURITY_PRINCIPAL, userdn);     
    env.put(Context.SECURITY_CREDENTIALS, password);     
    try {          
    System.setErr(new PrintStream(new FileOutputStream(new File("data.txt"))));     
    // Create the initial directory context     
    DirContext ctx = new InitialDirContext(env);          
    // Ask for all attributes of the object      
    Attributes attrs = ctx.getAttributes("cn=" + userName);          
    NamingEnumeration ne = attrs.getAll();                    
    while(ne.hasMore()){                         
    Attribute attr = (Attribute) ne.next();                                   
    if(attr.size() > 1){               
    for(Enumeration e = attr.getAll(); e.hasMoreElements() ;) {                                       
    System.err.println(attr.getID() + ": " + e.nextElement());                     
    } else {
         System.err.println(attr.getID() + ": " + attr.get());
    // Close the context when we're done     
    ctx.close();     
    } catch(javax.naming.NamingException ne) {
         System.err.println("Naming Exception: " + ne);     
    } catch(IOException ioe) {
         System.err.println("IO Exception: " + ioe);     

    That doesn't work either. It seems its not finding the NamingException class in any of the jar files. I don't know why? Any clues?

  • Connect to LDAP use JNDI SSL

    Hi all:
    I want to connect to a LDAP use SSL, my code is like following.
         Hashtable env = new Hashtable();
                   String ADuid = "user";
                   String ADpwd = "pwd";
                   env.put(Context.INITIAL_CONTEXT_FACTORY,
                        "com.sun.jndi.ldap.LdapCtxFactory");
                   env.put(Context.SECURITY_AUTHENTICATION,"simple");
                   env.put(Context.SECURITY_PRINCIPAL,ADuid);
                   env.put(Context.SECURITY_CREDENTIALS,ADpwd);
                   env.put(Context.SECURITY_PROTOCOL,"ssl");
                   env.put(Context.PROVIDER_URL, "ldaps://server address:636");
                   try {
                        System.setProperty("javax.net.ssl.trustStore","truststore");
                        System.setProperty("javax.net.ssl.trustStorePassword", 123456");
                        // Create the initial directory context
                        DirContext ctx = new InitialDirContext(env);
                   }catch(Exception ex){
                        wdComponentAPI.getComponent().getMessageManager().reportException(store + ex.toString(),false);
    These code is tested sucessful on java application. But can't work on webdynpro program, it reports an Exception "javax.naming.CommunicationException: simple bind failed Root exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found] "
    I've tryed to put the truststore on different DIR, but still not work. Does the method System.setProperty available on Web server? How to implement SSL certification?

    Hi Wayne Lou,
    I have same issue in connecting LDAP over SSL port 636 in Web Dynpro JAVA code.
    could you please share your solution code or guide me to solve my issue.
    Regards,
    Lakshmi Narayana Kodavati,

  • Errror during SSL connection with LDAP using JNDI APIs

    Hello,
    I have established a client and server certificates cert.arm for LDAP server and client. On client i have created a client.kdb file and on server server.kdb file both containing cert.arm. whwn i give a request
    C:\Program Files\IBM\LDAP\bin>ldapsearch -b "o=ibm,c=us" -h 9.182.174.71 -p 636 -D cn=roo
    -w root1 -Z -K "C:\Program Files\ibm\ldap\etc\client.kdb" -P client -s sub cn=s* cn sn
    it gave me proper results
    but using a JNDI API where i specify
    Hashtable env = new Hashtable(11);
         env.put(Context.INITIAL_CONTEXT_FACTORY,
         "com.sun.jndi.ldap.LdapCtxFactory");
         // Specify LDAPS URL
         env.put(Context.PROVIDER_URL, "ldap://"+"9.182.174.71:636");
         // Authenticate as S. User and password "mysecret"
         env.put(Context.SECURITY_PROTOCOL, "ssl");
         env.put(Context.SECURITY_AUTHENTICATION, "simple");
         env.put(Context.SECURITY_PRINCIPAL, "cn=root1");
         env.put(Context.SECURITY_CREDENTIALS, "root1");
    DirContext ctx = new InitialDirContext(env);
    SearchControls constraintssc=new SearchControls();
    constraintssc.setSearchScope(SearchControls.SUBTREE_SCOPE);
                             // performing the search
    NamingEnumeration results=ctx.search("o=ibm,c=us","cn=s*",constraintssc);
    ////etc.........
    Its gives me an exception saying that
    javax.naming.CommunicationException: simple bind failed: 9.182.174.71:636. Root
    exception is javax.net.ssl.SSLHandshakeException: Couldn't find trusted certificate
    Could any body help me out on this
    Thank You

    You are attempting to authenticate via an SSL connection to port 636.
    The message 'couldn't find trusted certificate' means that your client doesn't trust the certificate it has received from the LDAP server.
    In order to establish that trust, you must export a certificate file from the LDAP server, then use Java's keytool.exe to create a keystore file using that certificate. Then your client code must reference that keystore file that you've created.
    So essentially, you have to provide your program the LDAP server's credentials. "If the server's certificate looks like this, then you can trust it."
    After your program trusts the certificate it receives from the server at runtime, your connection will authenticate.

  • How to get LDAP sub-error code using JNDI (MD5 or any other SASL mechanism)

    Hi All,
    My objective is to find out if a user name exists in LDAP/Active Directory. I understand that there are specific sub error codes, like below:
    · 525 - user not found
    · 52e - invalid credentials
    · 530 - not permitted to logon at this time
    · 532 - password expired
    · 533 - account disabled
    · 701 - account expired
    · 773 - user must reset password
    · 775 - account locked.
    When I tried with "simple" authentication, I am able to get exact reason code from which I can understand what went wrong.
    Here's the code snippet:
         Hashtable<String, Object> env = new Hashtable<String, Object>();
              env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    *     env.put(Context.SECURITY_AUTHENTICATION,"simple");*
              env.put(Context.SECURITY_PRINCIPAL, "myUser");
              env.put(Context.SECURITY_CREDENTIALS, "mySecret");
              env.put(Context.PROVIDER_URL, "ldap://10.10.10.10:389/");
              env.put("com.sun.jndi.ldap.trace.ber", System.err); //debug trace
              DirContext ctx = null;
         try {
                   ctx = new InitialLdapContext(env, null);
              } catch (javax.naming.AuthenticationException ae) {
                   System.out.println("Message: "+ae.getMessage());
                   ae.printStackTrace();
    Output:
    [LDAP: error code 49 - 80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, *data 525*, vece_
    From above output it's clear that the sub error code is 525, that means User Not Found
    If I want to achieve the same thing with Digest-MD5 algorithm, I am always getting sub error code as 0 from which I am not at all able to understand what went wrong.
    Here's my code snippet:
                 Hashtable<String, Object> env = new Hashtable<String, Object>();
              env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            *     env.put(Context.SECURITY_AUTHENTICATION,"Digest-MD5");*
              env.put(Context.SECURITY_PRINCIPAL, "myUser");
              env.put(Context.SECURITY_CREDENTIALS, "mySecret");
              env.put(Context.PROVIDER_URL, "ldap://10.10.10.10:389/");
              env.put("com.sun.jndi.ldap.trace.ber", System.err); //debug trace
              DirContext ctx = null;
                     try {
                   ctx = new InitialLdapContext(env, null);
              } catch (javax.naming.AuthenticationException ae) {
                   System.out.println("Message: "+ae.getMessage());
                   ae.printStackTrace();
    Output:
    [LDAP: error code 49 - 8009030C: LdapErr: DSID-0C09043E, comment: AcceptSecurityContext error, *data 0*, vece_
    From the above sub error code 0, it's very difficult to understand what went wrong with the credentails.
    Can any one help me out to find out what I am missing? Any help in this regard is highly appreciated.
    Please let me know if there's any other way to check if the user exists in  LDAP/Active Directory.
    Thanks a lot,
    Siva.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Thank you,
    As i was trying to obtain the input to UI from an xml file by which the axis converts to java objects and inturn have to get the reply as xml file . The error was in the jar files ,when i loaded the jar files another time my code started working.

  • Querying deleted objects container in Active Directory using JNDI

    Hi,
    I am trying to query deleted objects container using JNDI which fails with error 64.
    Has anyone seen this or knows how to query AD using binary data in JNDI.
    Seems to me there is some problem with the search base.
    search base: <GUID=18E2EA80684F11D2B9AA00C04F79F805,dc=engserver,dc=com>.
    filter: objectclass=*
    search scope: subtree
    This is the error:
    Search example failed.
    javax.naming.InvalidNameException: <GUID=18E2EA80684F11D2B9AA00C04F79F805,dc=eng
    server,dc=com>: [LDAP: error code 64 - 00000057: LdapErr: DSID-0C090563, comment
    : Error processing name, data 0, v893 ]; remaining name '<GUID=18E2EA80684F11D2B
    9AA00C04F79F805,dc=engserver,dc=com>'
    at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2802)
    at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2616)
    at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1744)
    at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1667)
    at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirCon
    text.java:368)
    at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCom
    positeDirContext.java:328)
    at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCom
    positeDirContext.java:313)
    at javax.naming.directory.InitialDirContext.search(InitialDirContext.jav
    a:245)
    at jSearch.main(jSearch.java, Compiled Code)
    Thanks,
    Chetan

    I thought I had posted one of these. How remiss of me !/**
    * deleted.java
    * 5 July 2001
    * Sample JNDI application to search for deleted objects
    * Modified December 2004 to add Win2K3 lastKnownParent
    import java.util.Hashtable;
    import javax.naming.*;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    import com.sun.jndi.ldap.ctl.*;
    class DeletedControl implements Control {
         public byte[] getEncodedValue() {
              return new byte[] {};
         public String getID() {
              return "1.2.840.113556.1.4.417";
         public boolean isCritical() {
              return true;
    public class deleted     {
         public static void main (String[] args)     {
              Hashtable env = new Hashtable();
              String adminName = "CN=Administrator,CN=Users,DC=ANTIPODES,DC=COM";
              String adminPassword = "XXXXXX";
              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 attributes to return
                   String returnedAtts[]={"distinguishedName","lastKnownParent"};
                   searchCtls.setReturningAttributes(returnedAtts);
                   //Specify the search scope
                   searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                   //specify the LDAP search filter
                   String searchFilter = "(&(objectClass=user)(isDeleted=TRUE))";
                   //Specify the Base for the search
                   String searchBase = "DC=antipodes,DC=com";
                   //initialize counter to total the results
                   int totalResults = 0;
                   //specify the Deleted control
                   Control[] rqstCtls = new Control[] {new DeletedControl()};
                   ctx.setRequestControls(rqstCtls);
                   //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();
                        totalResults++;
                        System.out.println(totalResults + ". " + sr.getName().toString());
                        // Print out some of the attributes, catch the exception if the attributes have no values
                        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();System.out.println("   " + e.next().toString()));
                             catch (NullPointerException e)     {
                             System.err.println("Problem listing attributes: " + e);
                   System.out.println("Deleted objects: " + totalResults);
                   ctx.close();
              catch (NamingException e) {
              System.err.println("Problem searching directory: " + e);
    }

  • Java JNDI LDAP connectivity problem.  NoSuchAttributeException

    Hello,
    I am trying to add a user to Active Directory server through LDAP. Following is the code I am using:
    ======================================================================
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://192.123.321.123:389");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "user1");
    env.put(Context.SECURITY_CREDENTIALS, "user123");
    try {
    System.out.println("68");
    Context ctx = new InitialContext(env);
    System.out.println("71");
    BasicAttribute oc = new BasicAttribute("objectclass", "top");
    oc.add("person");
    oc.add("organizationalperson");
    oc.add("User");
    BasicAttribute ouSet = new BasicAttribute("ou");
    ouSet.add("test");
    BasicAttributes attrs = new BasicAttributes(true);
    attrs.put(oc);
    attrs.put(ouSet);
    attrs.put("cn", "ndubey001");
    attrs.put("sn", "ndubey001");
    attrs.put("sAMAccountName", "ndubey001");
    attrs.put("givenName", "ndubey001");
    attrs.put("name", "ndubey001");
    ctx.bind("uid=ndubey001,ou=test,o=myserver.com", attrs);
    System.out.println("74");
    ctx.close();
    } catch (NamingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    ======================================================================
    I have tried with so many different combinations. Most of the times the parameters I am passing looks okay but I keep getting the same exception as follows:
    ======================================================================
    68
    71
    javax.naming.directory.NoSuchAttributeException: [LDAP: error code 16 - 00000057: LdapErr: DSID-0C090B38, comment: Error in attribute conversion operation, data 0, vece
    at com.sun.jndi.ldap.LdapCtx.mapErrorCode(Unknown Source)
         at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
         at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source)
         at com.sun.jndi.ldap.LdapCtx.c_bind(Unknown Source)
         at com.sun.jndi.ldap.LdapCtx.c_bind(Unknown Source)
         at com.sun.jndi.toolkit.ctx.ComponentContext.p_bind(Unknown Source)
         at com.sun.jndi.toolkit.ctx.PartialCompositeContext.bind(Unknown Source)
         at com.sun.jndi.toolkit.ctx.PartialCompositeContext.bind(Unknown Source)
         at javax.naming.InitialContext.bind(Unknown Source)
         at LDAPTest.main(LDAPTest.java:99)Coming out
    ======================================================================
    Can anyone tell what is the exact problem ?
    Cheers,
    Nitin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Too many errors to even consider correcting your code (objectClasses, UID attribute, ctx.create)....
    Refer to the following for a description & sample code:
    JNDI, Active Directory (Creating new users & demystifying userAccountControl
    http://forum.java.sun.com/thread.jspa?threadID=582103&tstart=15

Maybe you are looking for

  • Regarding clearing strategy in FI-CA

    Hello... This is pertaining to clearing strategy in FI-CA, when customer pays an extra amount against invoice it should go as payment on account but it is getting adjusted against next debit line item (i.e installments due for future dates). Our requ

  • Osx 10.6.8 slow after power outage

    My 2007 intel imac lost power a while back and has been slow and somewhat erratic since that happened. My area suffered a power interuption that lasted a couple of minutes. When i turned the machine on the next day I used the disk utility to verify t

  • Graphics Place holders - instead of images

    Hi Guys I am using ID4 and have set up various items that I repeatedly use in a library. Every time I drag over a library item that includes an image or two, the result is that I get the images as  Gray Placeholder boxes with diagonal lines through.

  • Rotten at the Core

    Hi all, I think I've messed with some files, so my computer now is without my desktop image (instead it is of a full grey), and it is without menubar icons (such as wifi, bt, eject, spotlight etc). Probably Core Services are not being launched? Is th

  • I have a fresh install of Lion and upgraded to Safari 6.0.5

    I have a fresh install of Lion and upgraded to Safari 6.0.5 installed all patches and updates. Crashes immediately upon launch. Sig_Sev. Error.