I have a working code snippet by which i can authenticate a user by dn
and password. My requirement is that the user will be entering his username(sAMAccountName
) and I want to authenticate using sAMAccountName
and password. How can I modify this code to achieve it?
String userName = "John P R-Asst General Manager";
String passWord = "asdfgh123";
String base ="OU=SOU,DC=example,DC=com";
Str开发者_Go百科ing dn = "cn=" + userName + "," + base;
String ldapURL = "ldap://mdsdc3.example.com:389";
authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
authEnv.put(Context.PROVIDER_URL, ldapURL);
authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
authEnv.put(Context.SECURITY_PRINCIPAL, dn);
authEnv.put(Context.SECURITY_CREDENTIALS, password);
try {
DirContext authContext = new InitialDirContext(authEnv);
return true;
} catch (NamingException namEx) {
return false;
}
I hope this helps many of you.
You don't need to all user hierarchy with CN, DN, etc.
You can login just passing domain\user and password.
I've my code working as it is bellow:
try
{
// Set up the environment for creating the initial context
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap_server:389");
//
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "domain\\user"); //we have 2 \\ because it's a escape char
env.put(Context.SECURITY_CREDENTIALS, "test");
// Create the initial context
DirContext ctx = new InitialDirContext(env);
boolean result = ctx != null;
if(ctx != null)
ctx.close();
return result;
}
catch (Exception e)
{
return false;
}
Can you try to complete Context.PROVIDER_URL
like this :
String ldapURL = "ldap://mdsdc3.example.com:389/DC=example,DC=com";
I Think it would be better to use GSSAPI, perhaps you can have a look here and here
精彩评论