/**
* A code example to demonstrate how StartTLS works
* Note: This example has been tested to work with Active Directory 2003
*/
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;
public class StartTSLJndiClient
{
public static void main (String[] args)
{
// To specify the trustStore, if any other than the default one:
// %JAVA_HOME%\lib\security\certs
System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "password"); // optional
// To spcify client's keyStore where client's certificate is located
// Note: Client's keyStore is optional for StartTLS negotiation and connection.
// But it is required for implicit client indendity assertion
// by SASL EXTERNAL where client ID is extracted from certificate subject.
System.setProperty("javax.net.ssl.keyStore", "myKey.pfx");
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.keyStorePassword", "secret");
Hashtable env = new Hashtable(5, 0.75f);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://myServerInDnsFullName:389");
try{
/* Establish LDAP association */
LdapContext ctx = new InitialLdapContext(env, null);
/* Requesting to start TLS on an LDAP association */
ExtendedRequest tlsRequest = new StartTlsRequest();
ExtendedResponse tlsResponse = ctx.extendedOperation(tlsRequest);
/* Starting TLS */
StartTlsResponse tls = (StartTlsResponse)tlsResponse;
tls.negotiate();
// A TLS/SSL secure channel has been established if you reach here.
/* Assertion of client's authorization Identity -- Explicit way */
ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, "testUser@myDomain");
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, "password");
Attributes result = ctx.getAttributes("uid=jdoe,cn=vip,dc=domain,dc=com");
System.out.println(result);
tls.close();
// The TLS/SSL secure layer has been closed and all traffic down the road
// will be in clear text.
/* other LDAP operations may go here */
/* ... */
ctx.close();
}catch(Exception e){
e.printStackTrace();
System.exit(-1);
}
}
}