Skip to content

Instantly share code, notes, and snippets.

@nyomo
Last active October 13, 2022 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyomo/23e5aadd1f3a7afa6505b3f4f41fc49b to your computer and use it in GitHub Desktop.
Save nyomo/23e5aadd1f3a7afa6505b3f4f41fc49b to your computer and use it in GitHub Desktop.
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
//以下のサイトのサンプルコードを自分で他人に説明する時に説明しやすい用に変更しました
//https://www.earthlink.co.jp/engineerblog/technology-engineerblog/3336/
public class LDAPClientTest {
public static void main(String[] args) throws NamingException {
String userId = "認証を試したいユーザ名";
String userPass = "userPassのパスワード";
final String LDAPuser = "LDAP認証用をさせる用にアカウントを作る@hogehoge.private";
final String LDAPpass = "LDAPuserのパスワード";
final String LDAPserver = "ldaps://ad01.hogehoge.private:636";
final String baseDn = "dc=hogehoge,dc=private";
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, LDAPserver);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL,LDAPuser);
env.put(Context.SECURITY_CREDENTIALS, LDAPpass);
DirContext dirContext = null;
try {
dirContext = new InitialDirContext(env);
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "sAMAccountName=";
NamingEnumeration<SearchResult> searchResult =
dirContext.search(baseDn, filter + userId, searchControls);
if (searchResult.hasMoreElements()) {
SearchResult sr = (SearchResult) searchResult.nextElement();
String userName = sr.getName();
if(userPass.isEmpty()){
System.out.println("password is empty");
throw new NamingException();
}
String password = userPass;
System.out.println(userName);
env.put(Context.SECURITY_PRINCIPAL, userName + "," + baseDn);
env.put(Context.SECURITY_CREDENTIALS, password);
dirContext = new InitialDirContext(env);
System.out.println("CertificationStatus.CR_OK");
return;
} else {
System.out.println("UserNotFound:" + userId);
return;
}
} catch (NamingException e) {
System.out.println("Search User fail or password fail");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dirContext.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment