Analytics


Google
Showing posts with label LDAP. Show all posts
Showing posts with label LDAP. Show all posts

Friday, November 30, 2012

JDBC Connection String to Use LDAP


If LDAP allows anonymous.
String ldapHost    = "ldap-server:389";
String context     = ",dc=nl,dc=abnamro,dc=com";
 
String serviceName = "mts-a-de-grid";
String user        = "aldo";
String pass        = "aldo";
String url         = "jdbc:oracle:thin:@ldap://" + ldapHost + "/" + instance + ldap_context;
 
OracleDataSource o = new OracleDataSource();
 
o.setUser(user);
o.setPassword(password);
o.setURL(url);
 
Connection conn = o.getConnection();

If authentication is required:
String url = "jdbc:oracle:thin:@ldap://ldap-server:389/CN=Admin,O=COHERIS,C=FR";
 
 
Properties prop = new Properties();
prop.put("java.naming.security.authentication", "simple");
prop.put("java.naming.security.principal","CN=Admin,O=COHERIS,C=FR");
prop.put("java.naming.security.credentials", "password");
 
OracleDataSource ods = new OracleDataSource();
ods.setURL(url);
ods.setConnectionProperties(prop);

Reference:
  Oracle Forum

Tuesday, April 13, 2010

Query LDAP using JNDI

The following is the best example I found that illustrates how to query LDAP using JNDI (in Java).  The code is found here.

One of the key things I found when writing the code is sometimes the attribute that we want may have a null value.  This can be handled by enclosing the code using a try ... catch.

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

public class SimpleQuery {

    public static void main(String[] args) {

        if (args.length != 2) {
          System.out.println("Syntax: SimpleQuery query attribute");
          return;
        }

        String query = args[0];
        String attribute = args[1];
        StringBuffer output = new StringBuffer();

        try {
            String url = "ldap://directory.cornell.edu/o=Cornell%20University,c=US";
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, url);
            DirContext context = new InitialDirContext(env);

            SearchControls ctrl = new SearchControls();
            ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration enumeration = context.search("", query, ctrl);
            while (enumeration.hasMore()) {
                SearchResult result = (SearchResult) enumeration.next();
                Attributes attribs = result.getAttributes();
                NamingEnumeration values = ((BasicAttribute) attribs.get(attribute)).getAll();
                while (values.hasMore()) {
                  if (output.length() > 0) {
                    output.append("|");
                  }
                  output.append(values.next().toString());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.print(output.toString());
    }

    public SimpleQuery() {}
}

Monday, November 24, 2008

Accessing LDAP using Java

The easiest way to access LDAP in Java is to use JNDI (Java Naming and Directory Interface).

A good example on how to do that can be obtained from Sun website. Snippet is as follows:


In the LDAP, authentication information is supplied in the "bind" operation. In LDAP v2, a client initiates a connection with the LDAP server by sending the server a "bind" operation that contains the authentication information.

In the LDAP v3, this operation serves the same purpose, but it is optional. A client that sends an LDAP request without doing a "bind" is treated as an anonymous client (see the Anonymous Authentication section for details). In the LDAP v3, the "bind" operation may be sent at any time, possibly more than once, during the connection. A client can send a "bind" request in the middle of a connection to change its identity. If the request is successful, then all outstanding requests that use the old identity on the connection are discarded and the connection is associated with the new identity.

The authentication information supplied in the "bind" operation depends on the authentication mechanism that the client chooses. See the next section for a discussion of the authentication mechanism.

Authenticating to the LDAP by Using the JNDI
In the JNDI, authentication information is specified in environment properties. When you create an initial context by using the InitialDirContext(in the API reference documentation) class (or its superclass or subclass), you supply a set of environment properties, some of which might contain authentication information. You can use the following environment properties to specify the authentication information.

* Context.SECURITY_AUTHENTICATION(in the API reference documentation) ("java.naming.security.authentication").
Specifies the authentication mechanism to use. For the Sun LDAP service provider, this can be one of the following strings: "none", "simple", sasl_mech, where sasl_mech is a space-separated list of SASL mechanism names. See the next section for a description of these strings.
* Context.SECURITY_PRINCIPAL(in the API reference documentation) ("java.naming.security.principal").
Specifies the name of the user/program doing the authentication and depends on the value of the Context.SECURITY_AUTHENTICATION property. See the next few sections in this lesson for details and examples.
* Context.SECURITY_CREDENTIALS(in the API reference documentation) ("java.naming.security.credentials").
Specifies the credentials of the user/program doing the authentication and depends on the value of the Context.SECURITY_AUTHENTICATION property. See the next few sections in this lesson for details and examples.

When the initial context is created, the underlying LDAP service provider extracts the authentication information from these environment properties and uses the LDAP "bind" operation to pass them to the server.

The following example shows how, by using a simple clear-text password, a client authenticates to an LDAP server.

// Set up the environment for creating the initial context
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "mysecret");

// Create the initial context
DirContext ctx = new InitialDirContext(env);

// ... do something useful with ctx

Using Different Authentication Information for a Context
If you want to use different authentication information for an existing context, then you can use Context.addToEnvironment()(in the API reference documentation) and Context.removeFromEnvironment()(in the API reference documentation) to update the environment properties that contain the authentication information. Subsequent invocations of methods on the context will use the new authentication information to communicate with the server.

The following example shows how the authentication information of a context is changed to "none" after the context has been created.

// Authenticate as S. User and the password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "mysecret");

// Create the initial context
DirContext ctx = new InitialDirContext(env);

// ... do something useful with ctx

// Change to using no authentication
ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "none");

// ... do something useful with ctx

Authentication Failures
Authentication can fail for a number of reasons. For example, if you supply incorrect authentication information, such as an incorrect password or principal name, then an AuthenticationException(in the API reference documentation) is thrown.

Here's an example that is a variation of the previous example. This time, an incorrect password causes the authentication to fail.

// Authenticate as S. User and give an incorrect password
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "notmysecret");

This produces the following output.

javax.naming.AuthenticationException: [LDAP: Invalid Credentials]
at java.lang.Throwable.(Compiled Code)
at java.lang.Exception.(Compiled Code)
...

Because different servers support different authentication mechanisms, you might request an authentication mechanism that the server does not support. In this case, an AuthenticationNotSupportedException(in the API reference documentation) will be thrown.

Here's an example that is a variation of the previous example. This time, an unsupported authentication mechanism ("custom") causes the authentication to fail.

// Authenticate as S. User and the password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "custom");
env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "mysecret");

This produces the following output.

javax.naming.AuthenticationNotSupportedException: Unsupported value for java.naming.security.authentication property.
at java.lang.Throwable.(Compiled Code)
at java.lang.Exception.(Compiled Code)
at javax.naming.NamingException.(Compiled Code)
...

Thursday, August 14, 2008

Querying LDAP using .Net

To query LDAP using .Net, use System.DirectoryServices library.

Quickest way is as follows:

Dim LDAPEntry As DirectoryEntry
Dim LDAPStr as String = "ldap://ldap.blogspot.com/ou=people,o=blogspot.com,o=SDS"

LDAPStr = "LDAP://" & LDAPSrv & LDAPPostFix
LDAPEntry = New DirectoryEntry(LDAPStr)

Dim srch As New DirectorySearcher(LDAPEntry)
srch.Filter = "uid=1234"

Dim rslt As SearchResult
rslt = srch.FindOne
Dim tmpStr as String
Dim tmpObj as Object

Dim rsltPropCol As ResultPropertyCollection = rslt.Properties
For Each keyStr In rsltPropCol.PropertyNames
Try
For Each tmpObj In rslt.Properties(keyStr)
'This loop is there because in LDAP multiple entry is
'permitted for the same key.
'Also any object are permitted some of which cannot be
'converted into string
keyVal = Replace(CStr(tmpObj), "'", "")
Next
Catch ex As System.Exception
keyVal = ""
End Try
tmpStr = String.Format("key is {0}, value is {1}", keyStr, keyVal)
Console.Writeline(tmpStr)
Next

In the example above, the LDAPStr is made up, you need to refer to the one use by your company. The same is the filter.

One of the key things that is important is that the values can be object of any kind so you need to be careful when retrieving it and then assigning to the variables.

If you don't specify properties to load, it will return all the fields same as you do a select * in SQL. If you want to restrict the fields it returns then specify it before you call the FindOne method:
   srch.PropertiesToLoad.Add("mail")
srch.PropertiesToLoad.Add("dept")
srch.PropertiesToLoad.Add("telephonenumber")
srch.PropertiesToLoad.Add("title")


It is possible to use wildcard. In LDAP, "*" is the wildcard.

FindOne will return only one result. If you want more than one, then use FindAll as in:

Dim rsltList As SearchResultCollection
rsltList = srch.FindAll

You can then loop thru the collection as in

For each rslt in rsltList
...
Next

Authentication

You can also use LDAP for authentication. When you set the Directory.AuthenticationType.

For example, when you set the following:

LDAPEntry.AuthenticationType = AuthenticationTypes.ReadonlyServer

Then you need to have the username and password prior to calling FindOne or FindAll as in:

LDAPEntry.Username = "uid=" & uid & ",ou=people,o=blogspot.com,o=sds"
LDAPEntry.Password = pwd



If you just want to query, just set the authenticationType to none. You can see all the other enumerations here.