JAAS and JNDI (LDAP)

Hello,
I am using JAAS to connect to a Active Directory and login successfully (Authentication of the user). After the login, I want to get the users property like email address, phone number, ... from the Active Directory using JNDI. As I understand, to get connected to the AD with JNDI I have to use someting like:
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,ldapUserName);
env.put(Context.SECURITY_CREDENTIALS,ldapUserPassword);
My Problem is now, that I would like to take the user, which has connected to the AD with JASS for accessing the AD, but I do not have the ldapUserPassword from the JAAS Principal (the logged on user).
Is ther a way to use the current logged in user as LDAP (JNDI) user, or another way, to access the requested proeprties?
Thanks and Regards
Stefan

If had excatly the same problem.
In my my case I had a domain "testdomain.mycompany.com" and a domain controller "domaincontroller.mycompany.com" (maybe this is a misconfiguration?)
So I have set in the kerberos config file
[realms]
        TESTDOMAIN.MYCOMPANY.COM = {
                kdc = domaincontroller.mycompany.com
        }and the lpad connection url to "ldap://domaincontroller.mycompany.com/dc=testdomain,dc=mycompany,dc=com
This resulted in the error you have descibed.
Finally I put the following entry in the hosts file on my local PC
192.168.0.10 domaincontroller.testdomain.mycompany.com (192.168.0.10 is the ip address of the domain controller) and then it worked!

Similar Messages

  • Authenticate using JAAS and LDAP

    Hi,
    I am trying to authenticate a user using JAAS against LDAP. I am able to hit LDAP, but failing when it comes to authentication.
    Yes, I have made sure the user and password are right.
    Here is my code and error message. Would really appreciate if someone can tell me what am I doing wrong here.
    My 'jaas.config' file :
    JNDILogin {
         com.sun.security.auth.module.JndiLoginModule Required
         debug=true
         useFirstPass=false
         strongDebug=true
         tryFirstPass=true
         storePass=true
         user.provider.url="Ldap://xxx.xxx.xxx.xxx:389/CN=someSecurityService,OU=XX,OU=XXXXX,OU=XXXXXX,OU=XXXXX,OU=XXXXXX,DC=XXX,DC=XXXXX,DC=XXX"
    group.provider.url="Ldap://xxx.xxx.xxx.xxx:389/CN=someSecurityService,OU=XX,OU=XXXXX,OU=XXXXXX,OU=XXXXX,OU=XXXXXX,DC=XXX,DC=XXXXX,DC=XXX";
    My implementation class 'ClientSideSecurityImp,java' :
    import javax.security.auth.Subject;
    import javax.security.auth.callback.CallbackHandler;
    import javax.security.auth.login.LoginContext;
    import javax.security.auth.login.LoginException;
    import org.apache.log4j.*;
    import com.sun.security.auth.callback.TextCallbackHandler;
    import com.sun.security.auth.module.JndiLoginModule;
    * Filename is ClientSideSecurity.java
    public class ClientSideSecurityImp
    private static final Logger log = Logger
    .getLogger(ClientSideSecurityImp.class);
    private Subject activeSubject = null;
    private String userName = null;
    private String appName = null;
    private String viaMech = null;
    private LoginContext lc = null;
    public ClientSideSecurityImp(String appNameVal)
    this.appName = appNameVal;
    * (non-Javadoc)
    public boolean userAuthenticate() throws SecurityException//,
    // AuthenticationException
    boolean authenticated = false;
    String whereAmI = "ClientSideSecurityImp.UserAuthenticate()";
    CallbackHandler handler = null;
    JndiLoginModule jndi = new JndiLoginModule();
    handler = new TextCallbackHandler();
    if (lc == null)
    try
    lc = new LoginContext("JNDILogin", handler);
    lc.login();
    } catch (LoginException e)
    // TODO Auto-generated catch block
    e.printStackTrace();
    activeSubject = lc.getSubject();
    log.debug(activeSubject.toString());
    // if we return with no exeption then authentication was sucessful.
    authenticated = true;
    return authenticated;
    * @return success at removing the certificates.
    public boolean logout()
    String whereAmI = "ClientSideSecurityImp.logout()";
    boolean success = false;
    this.userName = "";
    this.activeSubject = null;
    return true;
    My test class with main 'ClientSideSecurityImpTest.java' :
    import org.apache.log4j.Logger;
    import org.apache.log4j.PropertyConfigurator;
    import com.jaas.ClientSideSecurityImp;
    import junit.framework.TestCase;
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class ClientSideSecurityImpTest extends TestCase
    private static ClientSideSecurityImp cssi = new ClientSideSecurityImp("MyApp");
    private static final Logger log = Logger.getLogger(ClientSideSecurityImp.class);
    public static void main(String[] args)
    PropertyConfigurator.configure("log4j.properties");
    boolean test = cssi.userAuthenticate();
    log.debug("**##$$##** Authenticated :" + test);
    Error I get :
    I get some error messages here that is expected as I have 'tryFirstPass=true' in my 'jaas.config' file. Then it asks for the user and password again. After that this is what I get:
    Ldap username: user
    Ldap password: password
              [JndiLoginModule] user entered username: user
              [JndiLoginModule] user entered password: password
              [JndiLoginModule]: User not found
    javax.naming.NoInitialContextException: Cannot instantiate class: =com.sun.jndi.ldap.LdapCtxFactory [Root exception is java.lang.ClassNotFoundException: =com/sun/jndi/ldap/LdapCtxFactory]
         at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:652)
         at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:243)
         at javax.naming.InitialContext.init(InitialContext.java:219)
         at javax.naming.InitialContext.<init>(InitialContext.java:175)
         at com.sun.security.auth.module.JndiLoginModule.attemptAuthentication(JndiLoginModule.java:496)
         at com.sun.security.auth.module.JndiLoginModule.login(JndiLoginModule.java:310)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at javax.security.auth.login.LoginContext.invoke(LoginContext.java:675)
         at javax.security.auth.login.LoginContext.access$000(LoginContext.java:129)
         at javax.security.auth.login.LoginContext$4.run(LoginContext.java:610)
         at java.security.AccessController.doPrivileged(Native Method)
         at javax.security.auth.login.LoginContext.invokeModule(LoginContext.java:607)
         at javax.security.auth.login.LoginContext.login(LoginContext.java:534)
         at com.jaas.ClientSideSecurityImp.userAuthenticate(ClientSideSecurityImp.java:58)
         at com.test.ClientSideSecurityImpTest.main(ClientSideSecurityImpTest.java:29)
    Caused by: java.lang.ClassNotFoundException: =com/sun/jndi/ldap/LdapCtxFactory
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:219)
         at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:42)
         at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:649)
         ... 17 more
              [JndiLoginModule] regular authentication failed
              [JndiLoginModule]: aborted authentication failed
    javax.security.auth.login.FailedLoginException: User not found
         at com.sun.security.auth.module.JndiLoginModule.attemptAuthentication(JndiLoginModule.java:624)
         at com.sun.security.auth.module.JndiLoginModule.login(JndiLoginModule.java:310)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at javax.security.auth.login.LoginContext.invoke(LoginContext.java:675)
         at javax.security.auth.login.LoginContext.access$000(LoginContext.java:129)
         at javax.security.auth.login.LoginContext$4.run(LoginContext.java:610)
         at java.security.AccessController.doPrivileged(Native Method)
         at javax.security.auth.login.LoginContext.invokeModule(LoginContext.java:607)
         at javax.security.auth.login.LoginContext.login(LoginContext.java:534)
         at com.jaas.ClientSideSecurityImp.userAuthenticate(ClientSideSecurityImp.java:58)
         at com.test.ClientSideSecurityImpTest.main(ClientSideSecurityImpTest.java:29)
    java.lang.NullPointerException
         at com.jaas.ClientSideSecurityImp.userAuthenticate(ClientSideSecurityImp.java:65)
         at com.jaas.ClientSideSecurityImpTest.main(ClientSideSecurityImpTest.java:29)
    Thanks in advance.

    The error message clear cut says that the JVM cannot find the class com.sun.jndi.ldap.LdapCtxFactory. Make sure the LDAP provider jar which contains this class is in your program's classpath.

  • Problem with JNDI/LDAP AND connection pool

    I'm a newbie to Java but am attempting to write a servlet that retrieves info use to populate the contents of drop down menus. I'd like to only have to do this once. The servlet also retrieves other data (e.g. user profile info, etc ...). I'd like to be able to use the connection pool for all of these operations but I'm getting a compile error:
    public class WhitePages extends HttpServlet {
    ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
    public static String m_servletPath = null;
    public static String cattrs = null;
    public static String guidesearchlist[] = {};
    public static int isLocalAddr = 0;
    private int aeCtr;
    private String[] sgDNArray;
    private HashMap sgDN2DNLabel = new HashMap();
    private HashMap sgDN2SearchGuide = new HashMap();
    private String strport;
    private int ldapport;
    private String ldaphost;
    private String ldapbinddn;
    private String ldapbindpw;
    private String ldapbasedn;
    private int maxsearchcontainers;
    private int maxsearchkeys;
    private String guidesearchbases;
    private String guidecontainerclass;
    private String strlocaladdr;
    private String providerurl;
    // my init method establishes the connection
    // pool and then retrieve menu data
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    String strport = config.getInitParameter("ldapport");
    ldapport = Integer.parseInt(strport);
    String strconts = config.getInitParameter("maxsearchcontainers");
    maxsearchcontainers = Integer.parseInt(strconts);
    String strkeys = config.getInitParameter("maxsearchkeys");
    maxsearchkeys = Integer.parseInt(strkeys);
    ldaphost = config.getInitParameter("ldaphost");
    ldapbinddn = config.getInitParameter("ldapbinddn");
    ldapbindpw = config.getInitParameter("ldapbindpw");
    ldapbasedn = config.getInitParameter("ldapbasedn");
    guidesearchbases = config.getInitParameter("guidesearchbases");
    guidecontainerclass = config.getInitParameter("guidecontainerclass");
    strlocaladdr = config.getInitParameter("localaddrs");
    providerurl = "ldap://" + ldaphost + ":" + ldapport;
    /* Set up environment for creating initial context */
    Hashtable env = new Hashtable(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerurl.toString());
    /* Enable connection pooling */
    env.put("com.sun.jndi.ldap.connect.pool", "true");
    StringTokenizer st = new StringTokenizer(guidesearchbases, ":" );
    String guidesearchlist[] = new String[st.countTokens()];
    for ( int i = 0; i < guidesearchlist.length; i++ ) {
    guidesearchlist[i] = st.nextToken();
    // Get a connection from the connection pool
    // and retrieve the searchguides
    StringBuffer asm = new StringBuffer(""); // This is the advanced search menu htmlobject buffer
    StringBuffer strtmpbuf = new StringBuffer(""); // This is the simple search menu htmlobject buffer
    try {
    StringBuffer filter = new StringBuffer("");
    filter.append("(objectclass=" + guidecontainerclass + ")");
    String[] attrList = {"dn","cn","searchguide"};
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(attrList);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String attrlabelkey;
    sgDNArray = new String[guidesearchlist.length];
    for( int i = 0; i < guidesearchlist.length; i++ ) {
    // Search each of the namingspaces where
    // searchguides exist then build
    // the dynamic menus from the result
    DirContext ctx = new InitialDirContext(env);
    NamingEnumeration results = ctx.search(guidesearchlist, filter, ctls);
    I get a compile error:
    WhitePages.java:164: cannot resolve symbol
    symbol : method search (java.lang.String,java.lang.StringBuffer,javax.naming.directory.SearchControls)
    location: interface javax.naming.directory.DirContext
    NamingEnumeration results = ctx.search(guidesearchlist[i], filter, ctls);
    ^
    WhitePages.java:225: cannot resolve symbol
    symbol : variable ctx
    location: class OpenDirectory
    ctx.close();
    ^
    Can anyone help? If there is someone out there with JNDI connection pool experience I would appreciate your assistance!

    Manish
    The issue may not be related to the number of connections or the initial
    connections. Check your heap size (ms, mx). Turn on verbosegc. Your heap may
    not be big enough to accept the 25,000 rows.
    Bernie
    "Manish Kumar Singh" <[email protected]> wrote in message
    news:3e6c34ca$[email protected]..
    We are creating the result set with 25000 rows(each row has 56 columns) bygetting the connection using data source. With the initial capacity of the
    connection pool is 5 and the max capacity as 30 and grow connection as 1,
    the server gets out of memory exception, when we issue a new request, even
    after closing the previous connections.
    Now, if we change the initial capacity to 1 and rest all the things assame, the issue gets resolved and the server works fine.
    Could you please help me out in this regard????
    thanks in advance
    manish

  • JNDI, LDAP, and Weblogic 6.0

    Hi-
    We are encountering an issue with JNDI and spurious "socket closed"
    exceptions. The players in our environment are Weblogic 6.0, Netscape
    Directory Server 4.1, (both running on Solaris 2.8) and JNDI as of JDK 1.3.
    We do JNDI lookups to connect to LDAP and most of the time everything works
    fine. Occasionally we get the following exception.
    java.lang.NullPointerException
    at com.sun.jndi.ldap.Connection.run(Connection.java:568)
    at java.lang.Thread.run(Thread.java:484)
    Exception encountered: Socket closed
    javax.naming.CommunicationException: Socket closed. Root exception is
    java.net.SocketException: Socket closed
    at java.net.SocketOutputStream.socketWrite(Native Method)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:83)
    at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:72)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:130)
    at com.sun.jndi.ldap.Connection.writeRequest(Connection.java:210)
    at com.sun.jndi.ldap.LdapClient.search(LdapClient.java:497)
    at com.sun.jndi.ldap.LdapCtx.doSearch(LdapCtx.java:1720)
    at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1584)
    at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1509)
    at
    com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirContext.ja
    va:371)
    at
    com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeD
    irContext.java:331)
    at
    com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeD
    irContext.java:316)
    at
    javax.naming.directory.InitialDirContext.search(InitialDirContext.java:241)
    at adpsis.posse.ldap.LDAPReader.find(LDAPReader.java:37)
    at adpsis.posse.prfpos.PreferencesEJB.getUserName(PreferencesEJB.java:589)
    at
    adpsis.posse.prfpos.PreferencesEJB.getColorAttributes(PreferencesEJB.java:39
    1)
    at
    adpsis.posse.prfpos.PreferencesEJB.getColorPreferences(PreferencesEJB.java:3
    02)
    at
    adpsis.posse.prfpos.PreferencesEJBImpl.getColorPreferences(PreferencesEJBImp
    l.java:250)
    at
    adpsis.posse.prfpos.PreferencesEJBEOImpl.getColorPreferences(PreferencesEJBE
    OImpl.java:287)
    at
    adpsis.posse.prfpos.PreferencesEJBEOImpl_WLSkel.invoke(PreferencesEJBEOImpl_
    WLSkel.java:116)
    at
    weblogic.rmi.internal.BasicServerAdapter.invoke(BasicServerAdapter.java:373)
    at
    weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerRef.java
    :128)
    at
    weblogic.rmi.internal.BasicServerAdapter.invoke(BasicServerAdapter.java:237)
    at
    weblogic.rmi.internal.BasicRequestHandler.handleRequest(BasicRequestHandler.
    java:118)
    at
    weblogic.rmi.internal.BasicRequestDispatcher.dispatch(BasicRequestDispatcher
    .java:115)
    at weblogic.rmi.internal.ServerRequest.sendOneWayRaw(ServerRequest.java:88)
    at weblogic.rmi.internal.ServerRequest.sendReceive(ServerRequest.java:108)
    at
    weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java
    :247)
    at
    weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java
    :225)
    at
    adpsis.posse.prfpos.PreferencesEJBEOImpl_WLStub.getColorPreferences(Preferen
    cesEJBEOImpl_WLStub.java:221)
    at adpsis.posse.transformer.CSSServlet.doPost(CSSServlet.java:86)
    at adpsis.posse.transformer.CSSServlet.doGet(CSSServlet.java:214)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:748)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at
    weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java
    :213)
    at
    weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletCo
    ntext.java:1265)
    at
    weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java
    :1631)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    The only way to recover is to restart the Weblogic server. The LDAP server
    appears to be running normally and continues to service other instances of
    Weblogic. No errors are logged in the LDAP server, the JNDI lookup that
    establishes the DirContext works fine on restart and is used multiple times
    with no issues until..poof..socket closed. I'm not certain which part is at
    issue, Weblogic, LDAP, or JNDI.
    Any ideas?
    Regards,
    Brett Schmoll
    ADP/SIS

    WLS 6.0 will be supported in the next release of WLCS, which is due in the
    spring.
    - Ginny
    "aamerG" <[email protected]> wrote in message
    news:3a5cb774$[email protected]..
    Hi everyone,
    we are starting a new development project and would like to use Weblogic
    6.0. How soon do you think there we be a version of WLCS which works with
    6.0.
    TIA

  • Problem with OpenLDAP and JNDI

    I'm having problem working with OpenLDAP and JNDI.
    First I have changed LDAP's slapd.conf file:
    suffix          "dc=antipodes,dc=com"
    rootdn          cn=Manager,dc=antipodes,dc=com
    directory     "C:/Program Files/OpenLDAP/data"
    rootpw          secret
    schemacheck offthan i used code below, to create root context:
    package test;
    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 MakeRoot {
         final static String ldapServerName = "localhost";
         final static String rootdn = "cn=Manager,dc=antipodes,dc=com";
         final static String rootpass = "secret";
         final static String rootContext = "dc=antipodes,dc=com";
         public static void main( String[] args ) {
                   // set up environment to access the server
                   Properties env = new Properties();
                   env.put( Context.INITIAL_CONTEXT_FACTORY,
                              "com.sun.jndi.ldap.LdapCtxFactory" );
                   env.put( Context.PROVIDER_URL, "ldap://" + ldapServerName + "/" );
                   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.
                             ctx.createSubcontext( rootContext );
                   } catch ( NameAlreadyBoundException nabe ) {
                             System.err.println( rootContext + " has already been bound!" );
                   } catch ( Exception e ) {
                             System.err.println( e );
    }this worked fine, I could see that by using "LDAP Browser/Editor".
    and then I tried to create group with code:
    package test;
    import java.util.Hashtable;
    import javax.naming.*;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    public class MakeGroup
         public static void main (String[] args)
              Hashtable env = new Hashtable();
              String adminName = "cn=Manager,dc=antipodes,dc=com";
              String adminPassword = "secret";
              String ldapURL = "ldap://127.0.0.1:389";
              String groupName = "CN=Evolution,OU=Research,DC=antipodes,DC=com";
              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 attributes to be associated with the new group
                        Attributes attrs = new BasicAttributes(true);
                   attrs.put("objectClass","group");
                   attrs.put("samAccountName","Evolution");
                   attrs.put("cn","Evolution");
                   attrs.put("description","Evolutionary Theorists");
                   //group types from IAds.h
                   int ADS_GROUP_TYPE_GLOBAL_GROUP = 0x0002;
                   int ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP = 0x0004;
                   int ADS_GROUP_TYPE_LOCAL_GROUP = 0x0004;
                   int ADS_GROUP_TYPE_UNIVERSAL_GROUP = 0x0008;
                   int ADS_GROUP_TYPE_SECURITY_ENABLED = 0x80000000;
                   attrs.put("groupType",Integer.toString(ADS_GROUP_TYPE_UNIVERSAL_GROUP + ADS_GROUP_TYPE_SECURITY_ENABLED));
                   // Create the context
                   Context result = ctx.createSubcontext(groupName, attrs);
                   System.out.println("Created group: " + groupName);
                   ctx.close();
              catch (NamingException e) {
                   System.err.println("Problem creating group: " + e);
    }got the error code: Problem creating group: javax.naming.directory.InvalidAttributeIdentifierException: [LDAP: error code 17 - groupType: attribute type undefined]; remaining name 'CN=Evolution,OU=Research,DC=antipodes,DC=com'
    I tried by creating organizational unit "ou=Research" from "LDAP Browser/Editor", and then running the same code -> same error.
    also I have tried code for adding users:
    package test;
    import java.util.Hashtable;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    import javax.naming.*;
    import javax.net.ssl.*;
    import java.io.*;
    public class MakeUser
         public static void main (String[] args)
              Hashtable env = new Hashtable();
              String adminName = "cn=Manager,dc=antipodes,dc=com";
              String adminPassword = "secret";
              String userName = "cn=Albert Einstein,ou=Research,dc=antipodes,dc=com";
              String groupName = "cn=All Research,ou=Research,dc=antipodes,dc=com";
              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, "ldap://127.0.0.1:389");
              try {
                   // Create the initial directory context
                   LdapContext ctx = new InitialLdapContext(env,null);
                   // Create attributes to be associated with the new user
                        Attributes attrs = new BasicAttributes(true);
                   //These are the mandatory attributes for a user object
                   //Note that Win2K3 will automagically create a random
                   //samAccountName if it is not present. (Win2K does not)
                   attrs.put("objectClass","user");
                        attrs.put("samAccountName","AlbertE");
                   attrs.put("cn","Albert Einstein");
                   //These are some optional (but useful) attributes
                   attrs.put("giveName","Albert");
                   attrs.put("sn","Einstein");
                   attrs.put("displayName","Albert Einstein");
                   attrs.put("description","Research Scientist");
                        attrs.put("userPrincipalName","[email protected]");
                        attrs.put("mail","[email protected]");
                   attrs.put("telephoneNumber","999 123 4567");
                   //some useful constants from lmaccess.h
                   int UF_ACCOUNTDISABLE = 0x0002;
                   int UF_PASSWD_NOTREQD = 0x0020;
                   int UF_PASSWD_CANT_CHANGE = 0x0040;
                   int UF_NORMAL_ACCOUNT = 0x0200;
                   int UF_DONT_EXPIRE_PASSWD = 0x10000;
                   int UF_PASSWORD_EXPIRED = 0x800000;
                   //Note that you need to create the user object before you can
                   //set the password. Therefore as the user is created with no
                   //password, user AccountControl must be set to the following
                   //otherwise the Win2K3 password filter will return error 53
                   //unwilling to perform.
                        attrs.put("userAccountControl",Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_PASSWORD_EXPIRED+ UF_ACCOUNTDISABLE));
                   // Create the context
                   Context result = ctx.createSubcontext(userName, attrs);
                   System.out.println("Created disabled account for: " + userName);
                   //now that we've created the user object, we can set the
                   //password and change the userAccountControl
                   //and because password can only be set using SSL/TLS
                   //lets use StartTLS
                   StartTlsResponse tls = (StartTlsResponse)ctx.extendedOperation(new StartTlsRequest());
                   tls.negotiate();
                   //set password is a ldap modfy operation
                   //and we'll update the userAccountControl
                   //enabling the acount and force the user to update ther password
                   //the first time they login
                   ModificationItem[] mods = new ModificationItem[2];
                   //Replace the "unicdodePwd" attribute with a new value
                   //Password must be both Unicode and a quoted string
                   String newQuotedPassword = "\"Password2000\"";
                   byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
                   mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
                   mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl",Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWORD_EXPIRED)));
                   // Perform the update
                   ctx.modifyAttributes(userName, mods);
                   System.out.println("Set password & updated userccountControl");
                   //now add the user to a group.
                        try     {
                             ModificationItem member[] = new ModificationItem[1];
                             member[0]= new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("member", userName));
                             ctx.modifyAttributes(groupName,member);
                             System.out.println("Added user to group: " + groupName);
                        catch (NamingException e) {
                              System.err.println("Problem adding user to group: " + e);
                   //Could have put tls.close()  prior to the group modification
                   //but it seems to screw up the connection  or context ?
                   tls.close();
                   ctx.close();
                   System.out.println("Successfully created User: " + userName);
              catch (NamingException e) {
                   System.err.println("Problem creating object: " + e);
              catch (IOException e) {
                   System.err.println("Problem creating object: " + e);               }
    }same error.
    I haven't done any chages to any schema manually.
    I know I'm missing something crucial but have no idea what. I have tried many other code from tutorials from net, but they are all very similar and throwing the same error I showed above.
    thanks in advance for help.

    I've solved this.
    The problem was that all codes were using classes from Microsoft Active Directory, and they are not supported in OpenLDAP (microsoft.schema in OpenLDAP is just for info). Due to this some fields are not the same in equivalent classes ("user" and "person").
    so partial code for creating user in root would be:
    import java.util.Hashtable;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    import javax.naming.*;
    import javax.net.ssl.*;
    import java.io.*;
    public class MakeUser
         public static void main (String[] args)
              Hashtable env = new Hashtable();
              String adminName = "cn=Manager,dc=antipodes,dc=com";
              String adminPassword = "secret";
              String userName = "cn=Albert Einstein,ou=newgroup,dc=antipodes,dc=com";
              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, "ldap://127.0.0.1:389");
              try {
                   // Create the initial directory context
                   LdapContext ctx = new InitialLdapContext(env,null);
                   // Create attributes to be associated with the new user
                        Attributes attrs = new BasicAttributes(true);
                                  attrs.put("objectClass","user");
                   attrs.put("cn","Albert Einstein");
                   attrs.put("userPassword","Nale");
                   attrs.put("sn","Einstein");
                   attrs.put("description","Research Scientist");
                   attrs.put("telephoneNumber","999 123 4567");
                   // Create the context
                   Context result = ctx.createSubcontext(userName, attrs);
                   System.out.println("Successfully created User: " + userName);
              catch (NamingException e) {
                   System.err.println("Problem creating object: " + e);
    }hope this will help anyone.

  • NullPointerException at com.sun.jndi.ldap.Connection.run(Connection.java:52

    We are using the Sun jndi 1.2.1 files from a Java client to
    access the IBM SecureWay Directory 3.2 server. Our test case is
    retrieving entries using the ctx.getAttributes (String, String[])
    method. Occasionally we are receiving the following error.
    java.lang.NullPointerException
    at com.sun.jndi.ldap.Connection.run(Connection.java:525)
    at java.lang.Thread.run(Thread.java:481)
    The java.lang.NullPointerException is coming from the Sun JNDI file.
    Our program is not catching this exception.
    Has anyone seen this problem before and have any ideas on how this can be resolved?

    Download and use LDAP 1.2.3 or JDK 1.3.1.
    The problem should go away.

  • Change (or add) a password to Active Directory with Java and JNDI

    I've create a new account in LDAP with attributs, It's ok. But a can't initialize the password, i've tryed some samples without result.
    Maybe it's a SSL problem (i don't know why, i read it somewhere).
    my code :
    import java.util.*;
    import java.io.*;
    import java.net.*;
    import javax.naming.Context;
    import javax.naming.NameAlreadyBoundException;
    import javax.naming.NamingException;
    import javax.naming.directory.DirContext;
    import javax.naming.directory.InitialDirContext;
    import javax.naming.directory.BasicAttributes;
    import javax.naming.directory.BasicAttribute;
    import javax.naming.directory.ModificationItem;
    public class addUser {
         private static final String UNICODE = "Unicode";
         private static final String UNICODE_PASSWORD = "unicodePwd";
         public addUser() {}
         private Hashtable env;
         private DirContext ctx;
         private void _initialize()
         String jndiURL = "ldap://DOMAINSRV:389/";
         String initialContextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
         String authenticationMode = "simple";
         String contextReferral = "ignore";
         String principal = "[email protected]";
         String credentials = "oce";
         env = new Hashtable();
         env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
         env.put(Context.PROVIDER_URL, jndiURL);
         env.put(Context.SECURITY_AUTHENTICATION, authenticationMode);
         env.put(Context.SECURITY_PRINCIPAL, principal);
         env.put(Context.SECURITY_CREDENTIALS, credentials);
         env.put(Context.REFERRAL, contextReferral);
         public boolean createUser()
         try
              ctx = new InitialDirContext(env);
              ctx.destroySubcontext("cn=FBXX,cn=users,DC=gedeon,DC=fr");
              BasicAttributes attrs = new BasicAttributes();
              BasicAttribute ocs = new BasicAttribute("objectclass");
              ocs.add("user");
              attrs.put(ocs);
              BasicAttribute sa = new BasicAttribute("sAMAccountName", "FBXX");
              attrs.put(sa);
              BasicAttribute na = new BasicAttribute("name", "FRANCOIS BERTOUX");
              attrs.put(na);
              BasicAttribute sn = new BasicAttribute("sn", "BERT");
              attrs.put(sn);
              BasicAttribute up = new BasicAttribute("userPrincipalName", "[email protected]");
              attrs.put(up);
              BasicAttribute ua = new BasicAttribute("userAccountControl", "512");
              attrs.put(ua);
              BasicAttribute dn = new BasicAttribute("displayName", "FRA BERT");
              attrs.put(dn);
              BasicAttribute gn = new BasicAttribute("givenName", "FRA");
              attrs.put(gn);
              BasicAttribute des = new BasicAttribute("description", "CECI EST MON TEST");
              attrs.put(des);
              BasicAttribute cp = new BasicAttribute("codePage", "0");
              attrs.put(cp);
              BasicAttribute cc = new BasicAttribute("countryCode", "0");
              attrs.put(cc);
              BasicAttribute it = new BasicAttribute("instanceType", "4");
              attrs.put(it);
              ctx.createSubcontext("cn=FBXX,cn=users,DC=gedeon,DC=fr", attrs);
              changePassword ("cn=FBXX,cn=users,DC=gedeon,DC=fr", "TOTO" , "FBX");
              ctx.close();
         catch (NameAlreadyBoundException nex)
              System.out.println("User ID is already in use, please select a different user ID ...");
         catch (Exception ex)
              System.out.println("Failed to create user account... Please verify the user information...");
              ex.printStackTrace();
         return true;
    public final void changePassword(
    String argRDN,
    String argOldPassword,
    String argNewPassword)
    throws NamingException
         ModificationItem modificationItem[] = new ModificationItem[2];
         try
              modificationItem[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("unicodePwd",(byte[])this.encodePassword(argOldPassword)));
              modificationItem[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE,new BasicAttribute("unicodePwd",(byte[])this.encodePassword(argNewPassword)));
         catch (UnsupportedEncodingException e1)
              System.out.println("changePassword(String argOldPassword, String argNewPassword)" +
              "Passwordchange failed: " + e1.toString());
              throw new RuntimeException(e1.toString());
         try
              ctx.modifyAttributes(argRDN, modificationItem);
         catch (NamingException e1)
              System.out.println(
              "changePassword(String argOldPassword, String argNewPassword)" +
              "Passwordchange failed : " + e1.toString());
              throw e1;
    private byte[] encodePassword(String pass) throws UnsupportedEncodingException
         final String ATT_ENCODING = "Unicode";
         // Agree with MS's ATTRIBUTE_CONSTRAINT
         String pwd = "\"" + pass +"\"";
         byte bytes[] = pwd.getBytes(ATTENCODING);
         // strip unicode marker
         byte bytes[] = new byte [_bytes.length - 2];
         System.arraycopy(_bytes, 2, bytes, 0,_bytes.length - 2);
         return bytes;
         public static void main(String[] args)
              addUser testUser = new addUser();
              testUser._initialize();
              testUser.createUser();
    And the result is :
    changePassword(String argOldPassword, String argNewPassword)Passwordchange failed : javax.naming.OperationNotSupportedException: [LDAP: erro
    r code 53 - 00002077: SvcErr: DSID-03190ADF, problem 5003 (WILL_NOT_PERFORM), data 0
    ]; remaining name 'cn=FBXX,cn=users,DC=gedeon,DC=fr'
    Failed to create user account... Please verify the user information...
    javax.naming.OperationNotSupportedException: [LDAP: error code 53 - 00002077: SvcErr: DSID-03190ADF, problem 5003 (WILL_NOT_PERFORM), data 0
    ]; remaining name 'cn=FBXX,cn=users,DC=gedeon,DC=fr'
    at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:2804)
    at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2677)
    at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2483)
    at com.sun.jndi.ldap.LdapCtx.c_modifyAttributes(LdapCtx.java:1285)
    at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_modifyAttributes(ComponentDirContext.java:253)
    at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.modifyAttributes(PartialCompositeDirContext.java:170)
    at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.modifyAttributes(PartialCompositeDirContext.java:159)
    at javax.naming.directory.InitialDirContext.modifyAttributes(InitialDirContext.java:144)
    at addUser.changePassword(addUser.java:129)
    at addUser.createUser(addUser.java:92)
    at addUser.main(addUser.java:167)
    And with "userPassword" no error but no change.
    Please, help.
    Thanks

    Hello!
    I have a new variant of the set password problem, and as i did not get any longer with a big running application i wrote a small standalone program to connect to an Active Directory server, and, hm, it works! I can login with a account which has administrator priveledges, i can set passwords, works fine, unless, and now it gets a little bit curious, unless i change the VM.
    Everything works fine with a jdk 1.5.0_07, but if i switch over to the fine new 1.6.0_16, the login works still but the change of a password leads to a not so fine javax.naming.OperationNotSupportedException: [LDAP: error code 53 - 0000001F: SvcErr: DSID-031A0FC0, problem 5003 (WILL_NOT_PERFORM), data 0.
    As i use the same cacerts file, i do not really understand what is failing here, anyone who has an idea?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • JNDI LDAP Simple attribute storave via DirContext extended class

    I just started looking into JNDI today to manipulate and view LDAP directories. I have been following this tutorial:
    http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-ldap.html?page=4
    The use an example where they just would like to create a context with simple attributes. This seems to work well with my project - having to interact with LDAP user/user group/host store, where the LDAP objects have already been implemented, and populated for that matter.
    I can see how you would create a User DirContext object that would be used to bind, and then actually create that user in the LDAP store. My problem is that when you do the reverse, and get the information from a user that already exists. Is it possible to re-use that User DirContext class? The only way I have seen to do it was is doing a search, or a getAttributes. I could see it working if you have another User class on top of the UserDircontext class, and then some sort of conversion, but it seems like there would be an easier way. Any thoughts? Thanks.

    at least you need cn= in front of the name.
    Here some more questions you may ask yourself:
    How do you know, that the requested object is in the database?
    What is its DN?
    Can you retrieve it using the ldap command line utilities like ldapsearch?
    What does context.list("") return?

  • Message: Cannot begin session. com/sun/jndi/ldap/ctl/PagedResultsControl

    When I try to request a simple reuest (getversion) from the drm wsdl I receive an error in the XML repsonse (see below).
    I read somewhere in the forum that I have to change the external direcortory provider in HSS from "MSAD" to LDAP/OID. But this can not be configured in HSS since I can not change the ID attribute (its greyed out).
    Does anyone knows how I can sole it: I think its related to: "message: Cannot begin session. com/sun/jndi/ldap/ctl/PagedResultsControl"
    Perhaps wrong or missing jar files in the connection configuration?
    Any help is welcome.
    Detlev
    <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
    <env:Header/>
    <env:Body>
    <env:Fault>
    <faultcode>env:Server</faultcode>
    <faultstring>Cannot getVersion.
    [Tue Feb 14 16:03:06 CET 2012] - Oracle EPM Foundation Agent
    Error in request: begin session (message: Cannot begin session. com/sun/jndi/ldap/ctl/PagedResultsControl)</faultstring>
    <detail>
    <DrmServiceException xmlns="http://drm.webservices.epm.oracle">
    <Message xmlns:ns2="http://drm.webservices.epm.oracle" xmlns="">Cannot getVersion.
    [Tue Feb 14 16:03:06 CET 2012] - Oracle EPM Foundation Agent
    Error in request: begin session (message: Cannot begin session. com/sun/jndi/ldap/ctl/PagedResultsControl)</Message>
    <Code xmlns:ns2="http://drm.webservices.epm.oracle" xmlns="">0</Code>
    </DrmServiceException>
    </detail>
    </env:Fault>
    </env:Body>
    </env:Envelope>

    Thanks for the repsonse.
    Its exactly how you explain it.
    Last thing I am dealing with (as var as I can see now) is getting a (generic/other) ldap connection in HSS to our MSAD.
    HSS userinterface comes up with an error just before showing the user list. (on the serverside I traced traffic (wireshark) and see that userinformation is indeed retrieved).
    But the frontend is juist not showing/ loading the information.
    the error"a communication error occured when loading the view pane" Than the screen keeps on loading for ever
    Oracle support tries to find out whats going wrong here.
    Detlev

  • Urgent!  LDAPRealm and JNDI provider

    I must setup ldap realm using Site Server. According to
    Service Pack 6, Sun's service provider doesn't work with
    Site Server. I set-up Netscapes's as was advised. The
    problem is that Weblogic can't find LdapContextFactory
    class file (part of ldapsp.jar). This is how it is setup in
    my StartWeblogic.cmd:
    WEBLOGIC_CLASSPATH=.\license;.\classes;.\lib;.\lib\ldapsp.jar;
    .\lib\weblogicaux.jar;.\lib\ldapfilt.jar;.\lib\ldapjdk.jar;
    .\myserver\serverclasses
    Also I tried to put it in my JAVA_CLASSPATH. JAR files are
    in LIB folder with other jar files. Weblogic sees all of
    them except these. I tried to use these libraries from a
    stand-alone client talking to directory server and it works
    fine.
    Please advise.
    Thank you, Boris
    Here is a console message:
    Unable to initialize server: weblogic.security.ldaprealm.LDAPException: could not
    get context - with nested exception:
    [java.lang.reflect.InvocationTargetException - with
    target exception:
    [javax.naming.NoInitialContextException: Cannot
    instantiate class:  com.netscape.jndi.ldap.LdapContextFactory  [Root exception is java.lang.ClassNotFoundException:
    com/netscape/jndi/ldap/LdapContextFactory ]]]
    fatal initialization exception
    weblogic.security.ldaprealm.LDAPException: could not
    get context - with nested exception:
    [java.lang.reflect.InvocationTargetException - with
    target exception:
    [javax.naming.NoInitialContextException: Cannot
    instantiate class: com.netscape.jndi.ldap.LdapContextFactory 
    [Root exception is java.lang.ClassNotFoundException:  com/netscape/jndi/ldap/LdapContextFactory ]]]
    at weblogic.security.ldaprealm.LDAPDelegate.getContext
    (LDAPDelegate.java:212)
    at weblogic.security.ldaprealm.LDAPDelegate.lookup
    (LDAPDelegate.java:232)
    at weblogic.security.ldaprealm.LDAPDelegate.search
    (LDAPDelegate.java:345)
    at weblogic.security.ldaprealm.LDAPDelegate.search
    (LDAPDelegate.java:354)
    at weblogic.security.ldaprealm.LDAPDelegate.getGroupMembers
    (LDAPDelegate.java:553)
    at weblogic.security.ldaprealm.LDAPDelegate.getGroup
    (LDAPDelegate.java:539)
    at weblogic.security.ldaprealm.LDAPDelegate.getGroup
    (LDAPDelegate.java:527)
    at weblogic.security.ldaprealm.LDAPRealm.getGroup
    (LDAPRealm.java:75)
    at weblogic.security.acl.CachingRealm.getGroup
    (CachingRealm.java:1420)
    at weblogic.security.acl.CachingRealm.getPrincipal
    (CachingRealm.java:1020)
    at weblogic.security.acl.CachingRealm.addPermission
    (CachingRealm.java:813)
    at weblogic.security.acl.CachingRealm.setupAcls
    (CachingRealm.java:802)
    at weblogic.security.acl.CachingRealm.<init>
    (CachingRealm.java:706)
    at weblogic.security.acl.CachingRealm.<init>
    (CachingRealm.java:564)
    at weblogic.t3.srvr.T3Srvr.initializeSecurity
    (T3Srvr.java:1750)
    at weblogic.t3.srvr.T3Srvr.start(T3Srvr.java:1086)
    at weblogic.t3.srvr.T3Srvr.main(T3Srvr.java:827)
    at java.lang.reflect.Method.invoke(Native Method)
    at weblogic.Server.startServerDynamically(Server.java:99)
    at weblogic.Server.main(Server.java:65)
    at weblogic.Server.main(Server.java:55)

    Exception in thread "main"
    java.security.NoSuchAlgorithmException: Algorithm
    PBEWithSHAANDTwofish-CBC not avai
    lable
    at javax.crypto.SunJCE_b.a(DashoA6275)Well, you're clearly not finding BC.
    Here's the deal.
    I have done the following:
    I have downloaded the bouncycastle for jdk 1.4 from
    bouncycastle.org.I read somewhere in there that i also
    had to download and change the jurisdiction.jar policy
    files shpped in the jce.Ive done that too. jurisdiction.jar? Not something I've ever had to do. Are you thinking of the unlimited-strength jars? Those are local_policy and US_export_policy.jar.
    I have also
    pasted the .jar file bouncycastle after i jarred it
    myselfYou re-jarred BC? That won't work - the jar has to be signed, or JCE complains. If you rejar it, it won't be signed correctly, and you'll get an error when JCE goes to load it.
    in the jre both in j2sdk as well as C:\program
    files\java\security. Providers go in lib/ext, not JAVA_HOME/security.
    However, after having done all that i still keep
    getting the same errorHave you added BC to the java.security file, as the second Provider? (You need to leave SunJCE as the first one) If not, and after you put the BC jarfile (untouched by you!) into lib/ext, add this code to the start of your app:Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    What am i doing wrong?Is there a complete proper site
    that tells u exactly what to do as to how to add this
    provider??http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/JCERefGuide.html#InstallProvider
    Do i perhaps need to include the bouncycastle provider
    in my code as well???You can - see above. But java.security is the file to modify if you want to add it statically.
    Grant

  • JNDI :: LDAP :: SSL :: howto trust all certificates

    hi @ all,
    currently i'm writing a jndi ldap wrapper java package which is intended to capsulate all the jndi stuff for the user of it so he only need to configure it's settings through a xml configuration file.
    now i'm on the point that i want to enable this package to communicate through a ssl secured connection. therefore i'v got two questions.
    first:
    how can i specify a keystore file other than the default jre keystore file to be used by jndi when connecting to the directory server through ssl?
    second:
    i do not like the default behaviour of the jsse which forces me and in fact all the future users of the package to having importet the server's certificate to such a keystore. i think this is not nice cause i want to enable my application to connect to the server independent to the certifacte it uses. it there any way to get the jndi (i think jsse in fact) to accept every certificate the server uses?
    it would be nice if someone could help me with this questions 'cause i did not get it working up to now.
    thx in advance
    dialsc

    morning,
    meanwhile i was able to answer the first question by my selfe.
    here's the answer:
    create a keystore with the following instruction:
    keytool -import -file server_cert.cer -keystore jssecacertsthan tell java to use the individual keystore with the following statement (before creating the DirContext):
    System.setProperty("javax.net.ssl.trustStore", "/path/to/the/individual/keystore/file/myKeystoreFile");that's it. now the ssl connection should work.
    but what about my second question. can anyone give a answer for it, please?
    regards
    dialsc

  • Com.sun.jndi.ldap

    Hi,
    Is anyone familiar with JNDI LDAP automatic discovery codes
    env.put(Context.PROVIDER_URL,
        ldap:///o=JNDITutorial,dc=example,dc=com);
    It seems that by using DNS that associate with multiple domain controllers, it would lock out user account if they enter wrong pw because LDAP provider will send the request to each of the associated DC at the same time.  I wonder if anyone run through this issue and if it is a JDK bug and if someone does, how to you work around it?
    Thanks,
    Jennifer

    Hi,
    did you also try the following timeout variables?
    env.put("com.sun.jndi.dns.timeout.initial", "2000");
    env.put("com.sun.jndi.dns.timeout.retries", "3");...
    Besides you specific problem you will find a probably interesting article about handling network timeouts her:
    http://www.javacoffeebreak.com/articles/network_timeouts/
    Regards
    Klaus

  • Help with EJB and JNDI, please

    Hello. My name is Santiago, and i am a student from the University of Valladolid, in Spain. I am newcome in the world of EJB, I have done the first EJB from de Sun tutorial (I�m using the Sun Java System Application Server PE 8.2) and now I am trying to improve it in that way: I have the EJB and the client in diferent machines conected.
    I am trying to understand how to use JNDI, but i have not good results :( I have read about using ldap but i dont know if it is apropiated, or if it is installed automaticaly with the sun aplication, or if i have to download and install it... i am not sure about anything :)
    This is my client�s code (part of it)
    Hashtable envirom = new Hashtable();
    envirom.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    envirom.put("java.naming.factory.url.pkgs","com.sun.enterprise.naming");
    envirom.put(Context.PROVIDER_URL,"iiop://Santiago:389");
    envirom.put(Context.PROVIDER_URL,"ldap://192.168.1.101:389");
    envirom.put(Context.SECURITY_AUTHENTICATION,"none");
    InitialContext ctx = new InitialContext(envirom);
    Object objref = ctx.lookup("java:comp/env/ejb/Multiplica");
    When I try to connect in local mode (client and EJB in the same machine) i get something like that:
    javax.naming.CommunicationException: 192.168.1.101:389 [Root exception is java.n
    et.ConnectException: Connection refused: connect]
    at com.sun.jndi.ldap.Connection.<init>(Connection.java:204)
    at com.sun.jndi.ldap.LdapClient.<init>(LdapClient.java:118)
    at com.sun.jndi.ldap.LdapClient.getInstance(LdapClient.java:1578)
    at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2596)
    at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:283)
    It is even worse when i try it in different machines:
    10-mar-2006... com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImp1<init>
    ADVERTENCIA: "IOP00410201: <COMM_FAILURE> Fallo de conexion: Tipo de socket: IIOP_CLEAR_TEXT;
    name of host: portatil; puerto: 3700"
    org.omg.CORBA.COMM_FAILURE: vmcid: SUN minor code:201 completed:No
    Both SSOO are XP and I have disabled Firewalls.
    PLEASE, if you colud help me It would fantastic, because I am in that trouble, i have tryed 1000 solutions but i am not able to understand it.
    Hoping you can help me.
    Santiago.

    This thread is now being followed up in:
    http://swforum.sun.com/jive/thread.jspa?threadID=64092

  • JNDI/LDAP socket connection life time

    Hi,
    I've got a basic object lookup and search for attributes on that object working. I do this by creating an
    new InitialDirContext
    and then using that context to do a search for att values.
    Now i want to do this for many clients, and using this process over and over suggests to me that a new network connection is made each time.
    I'd like to just keep the connection live, and change my context, how does one to that?

    Ok, a thread can't be complete w/o some code..
    I'm getting errors creating the subcontext
    javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]; remaining name 'uid=dmb,ou=people,
    acme.com,dc=ldapdev,dc=acme,dc=com'
    These credentials work fine when they are used as the initial context.
    import javax.naming.*;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    import java.util.*;
    public class LDAP2
         public static final String s_PrincipalRoot = "ou=people,o=acme.com,dc=ldapdev,dc=acme,dc=com";
        public static void main( String[] args )
            try
                Hashtable env = new Hashtable();
                env.put( Context.INITIAL_CONTEXT_FACTORY,
                    "com.sun.jndi.ldap.LdapCtxFactory");
                env.put( Context.PROVIDER_URL, "ldap://1.2.3.4:389");
                env.put( Context.SECURITY_AUTHENTICATION, "simple" );
                env.put( Context.SECURITY_PRINCIPAL, "uid=admin," + s_PrincipalRoot );
                env.put( Context.SECURITY_CREDENTIALS, "admin");
                // Create the initial context
                DirContext ctx = new InitialDirContext(env);
                   // Create the sub context
                ctx.addToEnvironment( Context.SECURITY_CREDENTIALS, "password" );
                String userP = "uid=dmb," + s_PrincipalRoot;
                DirContext subCtx = (DirContext) ctx.createSubcontext( userP );
                   Attributes atts = subCtx.getAttributes( userP );
                   Attribute att = atts.get( "uid" );
                   String value = (String) att.get();
                   System.out.println( "UserID = " + value );
            catch (Exception e)
                e.printStackTrace();
    }

  • Problem with creating Connection pool and JNDI, driver is not detected

    Hi,
    I have an issue with creating Connection Pool and JNDI.
    I'm using:
    - JDK 1.6
    - OS: Linux(ubuntu 8.10)
    - Netbeans IDE 6.5.1
    - Java EE 5.0
    - Apache Tomcat 6.0.18 Its lib directory contains all necessary jar files for Oracle database driver
    - Oracle 11g Enterprise
    My problem is that the Oracle database driver is not detected when I want to create a pool (it works pretty well and is detected without any problem when I create ordinary connection by DriverManager)
    Therefore after running:
    InitialContext ic = new InitialContext();
    Context context = (Context)ic.lookup("java:comp/env");
    DataSource dataSource = (DataSource)context.lookup("jdbc/oracle11g");
    Connection connection = dataSource.getConnection();and right after dataSource.getConnection() I have the following exception:
    org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'oracle.jdbc.OracleDriver'
    at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1136)
    at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
    at servlets.Servlet1.doPost(Servlet1.java:47)
    at servlets.Servlet1.doGet(Servlet1.java:29)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Thread.java:619)
    Caused by: java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:169)
    at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1130)
    ... 17 more
    My application context file (context.xml) is:
    <?xml version="1.0" encoding="UTF-8"?>
    <Context path="/WebApplication3">
      <Resource auth="Container"
                      driverClassName="oracle.jdbc.OracleDriver"
                      maxActive="8"
                      maxIdle="4"
                      name="jdbc/oracle11g"
                      username="scott"
                      password="tiger"
                      type="javax.sql.DataSource"
                      url="jdbc:oracle:thin:@localhost:1521:database01" />
    </Context>and my web.xml is:
        <resource-ref>
            <description>Oracle Datasource example</description>
            <res-ref-name>jdbc/oracle11g</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
        </resource-ref>
    ...I found similar threads in different forums including sun, such as
    http://forums.sun.com/thread.jspa?threadID=567630&start=0&tstart=0
    http://forums.sun.com/thread.jspa?threadID=639243&tstart=0
    http://forums.sun.com/thread.jspa?threadID=5312178&tstart=0
    , but no solution.
    As many suggest, I also tried to put context directly in the server.xml (instead of my application context) and referencing it by <ResourceLink /> inside my application context but it didn't work and instead it gave me the following message:
    org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '   ' for connect URL 'null'
    Has anyone succeeded in creating a connection pool with JNDI by using Tomcat 6 or higher ? If yes, could kindly explain about the applied method.
    Regards,

    Hello again,
    Finally I managed to run my application also with Tomcat 6.0.18. There was only two lines that had to be modified
    in the context.xml file (the context of my application project and not server's)
    Instead of writing
    <Context antiJARLocking="true" path="/WebApplication2">
        type="javax.sql.DataSource"
        factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
    </Context>we had to write:
    <Context antiJARLocking="true" path="/WebApplication2">
        type="oracle.jdbc.pool.OracleDataSource"
        factory="oracle.jdbc.pool.OracleDataSourceFactory"
    </Context>- No modification was needed to be done at server level (niether server.xml nor server context.xml)
    - I just added the ojdbc6.jar in $CATALINA_HOME/lib (I didn't even need to add it in WEB-INF/lib of my project)
    - The servlet used to do the test was the same that I presented in my precedent post.
    For those who have encountered my problem and are interested in the format of the web.xml and context.xml
    with Tomcat 6.0, you can find them below:
    Oracle server: Oracle 11g Enterprise
    Tomcat server version: 6.0.18
    Oracle driver: ojdbc.jar
    IDE: Netbeans 6.5.1
    The context.xml file of the web application
    <?xml version="1.0" encoding="UTF-8"?>
    <Context antiJARLocking="true" path="/WebApplication2">
        <Resource name="jdbc/oracle11g"
                  type="oracle.jdbc.pool.OracleDataSource"
                  factory="oracle.jdbc.pool.OracleDataSourceFactory"
                  url="jdbc:oracle:thin:@localhost:1521:database01"
                  driverClassName="oracle.jdbc.OracleDriver"
                  userName="scott"
                  password="tiger"
                  auth="Container"
                  maxActive="100"
                  maxIdle="30"
                  maxWait="10000"
                  logAbandoned="true"
                  removeAbandoned="true"
                  removeAbandonedTimeout="60" />
    </Context>The web.xml of my web application
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        <resource-ref>
            <description>Oracle Database 11g DataSource</description>
            <res-type>oracle.jdbc.pool.OracleDataSource</res-type>
            <res-auth>Container</res-auth>
            <res-ref-name>jdbc/oracle11g</res-ref-name>
        </resource-ref>
        <servlet>
            <servlet-name>Servlet1</servlet-name>
            <servlet-class>servlets.Servlet1</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Servlet1</servlet-name>
            <url-pattern>/Servlet1</url-pattern>
        </servlet-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>Ok, now I'm happy as the original problem is completely solved
    Regards

Maybe you are looking for

  • RFC to SOAP - Internet

    Hi I am working on RFC to SOAP scenorio. In the PI, if the internet access is closed. The interface is not working, even though i am able to open the target URL from PI internet browser. In the PI, if the internet access is provided. The interface is

  • Cannot copy file with other buffer sizes, except 1

    Hi, i'd like to copy files (txt, images, etc) , but by using the following route: -read bytes from a file in a ByteBuffer -use a byte array to create a String representation in binary form (ie "0101101") of the ByteBuffer -print the string and then t

  • Compatible video cards supported by FMLE 3

    Dear All, Wondering to ask about any updated (2Q 2008 or 1Q 2009) link to the list of compatible video cards supported by Flash Media Live Encoder (FMLE) last Version 3.0. Thanks a lot, Cheers, Soares

  • Report is truncating in background

    Hi All, I am running one report having 35 columns in background. I am able to get only 20 fields and all other fields are truncated .My requirement is to run program in background and i have to download  all the records into desktop . I am working wi

  • Restricted Group as like as domain admins

    I have configure Restricted Group in GPO in mydomains.com. So I added a group called 'ABC_Support' and on the second box (This is group is a member of) was Administrators. in ABC_Support group, there is one user called 'tech_admin'.  Result: GPO was