Created
April 28, 2015 15:46
-
-
Save michaelames/f16ee975ddad15cf3527 to your computer and use it in GitHub Desktop.
Simplest possible example of Java authentication to LDAP Server (including Active Directory)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Hashtable; | |
import java.io.Console; | |
import javax.naming.Context; | |
import javax.naming.directory.DirContext; | |
import javax.naming.directory.InitialDirContext; | |
public class TestAuth { | |
public static void main(String[] args) { | |
TestAuth authentication = new TestAuth(); | |
try { | |
// Get the username and password | |
Console console = System.console(); | |
String userID = console.readLine("User ID: "); | |
String pwd = String.valueOf(console.readPassword("Password? ")); | |
// set up the LDAP parameters | |
Hashtable<Object, Object> env = new Hashtable<Object, Object>(); | |
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); | |
env.put(Context.PROVIDER_URL, "ldap://your.ad.server.here:389"); | |
env.put(Context.SECURITY_AUTHENTICATION, "simple"); | |
env.put(Context.REFERRAL, "follow"); | |
env.put(Context.SECURITY_PRINCIPAL, userID); | |
env.put(Context.SECURITY_CREDENTIALS, pwd); | |
// attempt to authenticate | |
DirContext ctx = new InitialDirContext(env); | |
ctx.close(); | |
System.out.println("\n*** Authenticated ***\n"); | |
} catch (Exception e) { | |
// if failure, tell us about errors | |
e.printStackTrace(); | |
System.out.println("\n*** Not Authenticated ***\n"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, at line 11 you have defined a reference to and created an unused and void object (except for what he takes from Object superclass) .
You just have defined a static main method for Class TestAuth , so what is the scope of "authentication" variable and his referenced (new) Object?