Implementation method:
Import java.util.Hashtable;
Import Javax.naming.Context;
Import javax.naming.NamingEnumeration;
Import Javax.naming.ldap.InitialLdapContext;
Import Javax.naming.ldap.LdapContext;
public class Ldapauth {
private String domain;
Private String Ldaphost;
Private String searchbase;
Public Ldapauth () {
This.domain = "{domain}";
This.ldaphost = "ldap://{ip}:{port}";
This.searchbase = "DC={DC},DC={DC}";
}
Public Ldapauth (String domain,string host,string dn) {
This.domain = domain;
This.ldaphost = host;
This.searchbase = DN;
}
public boolean Authldap (String username,string pass) {
String Searchfilter = "(& (Objectclass=user) (samaccountname=" + username + "))";
Hashtable env = new Hashtable ();
Env.put (Context.initial_context_factory, "com.sun.jndi.ldap.LdapCtxFactory");
Env.put (Context.provider_url, ldaphost);
Env.put (Context.security_authentication, "simple");
Env.put (Context.security_principal, username + "@" + domain);
Env.put (context.security_credentials, pass);
Ldapcontext CTXGC = null;
Boolean ldapuser = false;
try {
CTXGC = new Initialldapcontext (env,null);
Namingenumeration answer = Ctxgc.search (Searchbase, searchfilter,null);
if (answer!=null) {
Ldapuser = true;
}
} catch (Exception e) {
Todo:handle exception
}
return ldapuser;
}
Test:
User name password is correct:
User name password error:
JAVA Windows domain Certification Guide