I'm new to java LDAP authentication using JNDI. When shearching over internet for tutorials, I found a sample code from fallowing URL,
http://www.javaxt.com/Tutorials/Windows/How_to_Authenticate_Users_with_Active_Directory
I'm creating web app using JavaServlet & JSP.
Just I want is Authenticate users using LDAP.
My server is Apache,Tomcat and I'm using Xampp for that.
Now the system is authenticating users well using LDAP but some times it will throwing fallowing exception.
"javax.naming.NamingException: Failed to connect to xxxxxx.com"
It will remain about an hour, automatically system will again working well.
can any one tell me what would be the issue?
I have changed the server to GlassFish, but issue is same.
Here my code,
public static LdapContext getConnection (String username, String password,
String domainName, String serverName) throws NamingException {
if (domainName == null) {
try {
String fqdn = java.net.InetAddress.getLocalHost()
.getCanonicalHostName();
if (fqdn.split("\\.").length > 1) {
domainName = fqdn.substring(fqdn.indexOf(".") + 1);
}
} catch (java.net.UnknownHostException e) {
}
}
if (password != null) {
password = password.trim();
if (password.length() == 0) {
password = null;
}
}
Hashtable props = new Hashtable();
String principalName = username + "@" + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
if (password != null) {
props.put(Context.SECURITY_CREDENTIALS, password);
}
String ldapURL = "ldap://"
+ ((serverName == null) ? domainName : serverName + "."
+ domainName) +":389/";
String Auth_Metho="simple";
props.put(Context.SECURITY_AUTHENTICATION,
Auth_Metho);
props.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, ldapURL);
props.put("com.sun.jndi.ldap.read.timeout", "0");
try {
return new InitialLdapContext(props, null);
} catch (javax.naming.CommunicationException e) {
throw new NamingException("Failed to connect to " + domainName
+ ((serverName == null) ? "" : " through " + serverName));
} catch (NamingException e) {
throw new NamingException("Failed to authenticate " + username
+ "@" + domainName
+ ((serverName == null) ? "" : " through " + serverName));
}
}
//Then call it as....
String SreverName = "xxxxxx.com";
String userName = "xxxxx";
String password ="xxxxx";
LdapContext ctx;
try {
ctx = ActiveDirectory.getConnection( userName ,
password , SreverName);
ctx.close(); // unameStr, passStr,
System.out.println("Authenticated!");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}