JNDI 连接Windows Active Directory 教程(转)

论坛 期权论坛 脚本     
匿名技术用户   2021-1-7 07:48   36   0
java 代码
  1. /***************************** LDAPFastBind.java *****************/
  2. package test.ldap;
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.util.Hashtable;
  6. import javax.naming.AuthenticationException;
  7. import javax.naming.Context;
  8. import javax.naming.NamingEnumeration;
  9. import javax.naming.NamingException;
  10. import javax.naming.directory.Attribute;
  11. import javax.naming.directory.Attributes;
  12. import javax.naming.directory.BasicAttribute;
  13. import javax.naming.directory.BasicAttributes;
  14. import javax.naming.directory.DirContext;
  15. import javax.naming.directory.ModificationItem;
  16. import javax.naming.directory.SearchControls;
  17. import javax.naming.directory.SearchResult;
  18. import javax.naming.ldap.Control;
  19. import javax.naming.ldap.InitialLdapContext;
  20. import javax.naming.ldap.LdapContext;
  21. import javax.naming.ldap.StartTlsRequest;
  22. import javax.naming.ldap.StartTlsResponse;
  23. class FastBindConnectionControl implements Control {
  24. public byte[] getEncodedValue() {
  25. return null;
  26. }
  27. public String getID() {
  28. return "1.2.840.113556.1.4.1781";
  29. }
  30. public boolean isCritical() {
  31. return true;
  32. }
  33. }
  34. public class LDAPFastBind {
  35. public Hashtable env = null;
  36. public LdapContext ctx = null;
  37. public Control[] connCtls = null;
  38. public LDAPFastBind(String ldapurl) {
  39. env = new Hashtable();
  40. env.put(Context.INITIAL_CONTEXT_FACTORY,
  41. "com.sun.jndi.ldap.LdapCtxFactory");
  42. env.put(Context.SECURITY_AUTHENTICATION, "simple");
  43. env.put(Context.PROVIDER_URL, ldapurl);
  44. env.put(Context.SECURITY_PROTOCOL,"ssl");
  45. String keystore = "/jdk1.5.0_09/jre/lib/security/cacerts";
  46. System.setProperty("javax.net.ssl.trustStore",keystore);
  47. connCtls = new Control[] { new FastBindConnectionControl() };
  48. // first time we initialize the context, no credentials are supplied
  49. // therefore it is an anonymous bind.
  50. try {
  51. ctx = new InitialLdapContext(env, connCtls);
  52. } catch (NamingException e) {
  53. System.out.println("Naming exception " + e);
  54. }
  55. }
  56. public boolean Authenticate(String username, String password) {
  57. try {
  58. ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, username);
  59. ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
  60. ctx.reconnect(connCtls);
  61. System.out.println(username + " is authenticated");
  62. return true;
  63. }
  64. catch (AuthenticationException e) {
  65. System.out.println(username + " is not authenticated");
  66. System.out.println(e);
  67. return false;
  68. } catch (NamingException e) {
  69. System.out.println(username + " is not authenticated");
  70. System.out.println(e);
  71. return false;
  72. }
  73. }
  74. public void finito() {
  75. try {
  76. ctx.close();
  77. System.out.println("Context is closed");
  78. } catch (NamingException e) {
  79. System.out.println("Context close failure " + e);
  80. }
  81. }
  82. public void printUserAccountControl() {
  83. try {
  84. // Create the search controls
  85. SearchControls searchCtls = new SearchControls();
  86. // Specify the search scope
  87. searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  88. // specify the LDAP search filter
  89. //String searchFilter = "(&(objectClass=user)(CN=test))";
  90. //String searchFilter = "(&(objectClass=group))";
  91. String searchFilter = "(&(objectClass=user)(CN=peter lee))";
  92. // Specify the Base for the search
  93. String searchBase = "DC=joeyta,DC=local";
  94. // initialize counter to total the group members
  95. int totalResults = 0;
  96. // Specify the attributes to return
  97. String returnedAtts[] = { "givenName", "mail" };
  98. searchCtls.setReturningAttributes(returnedAtts);
  99. // Search for objects using the filter
  100. NamingEnumeration answer = ctx.search(searchBase, searchFilter,
  101. searchCtls);
  102. // Loop through the search results
  103. while (answer.hasMoreElements()) {
  104. SearchResult sr = (SearchResult) answer.next();
  105. System.out.println(">>>" + sr.getName());
  106. // Print out the groups
  107. Attributes attrs = sr.getAttributes();
  108. if (attrs != null) {
  109. try {
  110. for (NamingEnumeration ae = attrs.getAll(); ae
  111. .hasMore();) {
  112. Attribute attr = (Attribute) ae.next();
  113. System.out.println("Attribute: " + attr.getID());
  114. for (NamingEnumeration e = attr.getAll(); e
  115. .hasMore(); totalResults++) {
  116. System.out.println(" " + totalResults + ". "
  117. + e.next());
  118. }
  119. }
  120. } catch (NamingException e) {
  121. System.err.println("Problem listing membership: " + e);
  122. }
  123. }
  124. }
  125. System.out.println("Total attrs: " + totalResults);
  126. }
  127. catch (NamingException e) {
  128. System.err.println("Problem searching directory: " + e);
  129. }
  130. }
  131. public boolean adminChangePassword(String sUserName, String sNewPassword){
  132. try {
  133. //set password is a ldap modfy operation
  134. ModificationItem[] mods = new ModificationItem[1];
  135. //Replace the "unicdodePwd" attribute with a new value
  136. //Password must be both Unicode and a quoted string
  137. String newQuotedPassword = "\"" + sNewPassword + "\"";
  138. byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
  139. mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
  140. // Perform the update
  141. ctx.modifyAttributes(sUserName, mods);
  142. System.out.println("Reset Password for: " + sUserName);
  143. return true;
  144. }
  145. catch (NamingException e) {
  146. System.out.println("Problem resetting password: " + e);
  147. }
  148. catch (UnsupportedEncodingException e) {
  149. System.out.println("Problem encoding password: " + e);
  150. }
  151. return false;
  152. }
  153. public boolean userChangePassword(String sUserName, String sOldPassword, String sNewPassword){
  154. try {
  155. //StartTlsResponse tls = (StartTlsResponse)ctx.extendedOperation(new StartTlsRequest());
  156. //tls.negotiate();
  157. //change password is a single ldap modify operation
  158. //that deletes the old password and adds the new password
  159. ModificationItem[] mods = new ModificationItem[2];
  160. //Firstly delete the "unicdodePwd" attribute, using the old password
  161. //Then add the new password,Passwords must be both Unicode and a quoted string
  162. String oldQuotedPassword = "\"" + sOldPassword + "\"";
  163. byte[] oldUnicodePassword = oldQuotedPassword.getBytes("UTF-16LE");
  164. String newQuotedPassword = "\"" + sNewPassword + "\"";
  165. byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
  166. mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("unicodePwd", oldUnicodePassword));
  167. mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
  168. // Perform the update
  169. ctx.modifyAttributes(sUserName, mods);
  170. System.out.println("Changed Password for: " + sUserName);
  171. //tls.close();
  172. return true;
  173. }
  174. catch (NamingException e) {
  175. System.err.println("Problem changing password: " + e);
  176. }
  177. catch (UnsupportedEncodingException e) {
  178. System.err.println("Problem encoding password: " + e);
  179. } catch ( Exception e){
  180. System.err.println("Problem: " + e);
  181. }
  182. return false;
  183. }
  184. public boolean createNewUser(String sGroupName, String sUserName){
  185. try {
  186. // Create attributes to be associated with the new user
  187. Attributes attrs = new BasicAttributes(true);
  188. //These are the mandatory attributes for a user object
  189. //Note that Win2K3 will automagically create a random
  190. //samAccountName if it is not present. (Win2K does not)
  191. attrs.put("objectClass","user");
  192. attrs.put("sAMAccountName","AlanT");
  193. attrs.put("cn","Alan Tang");
  194. //These are some optional (but useful) attributes
  195. attrs.put("givenName","Alan");
  196. attrs.put("sn","Tang");
  197. attrs.put("displayName","Alan Tang");
  198. attrs.put("description","Engineer");
  199. attrs.put("userPrincipalName","alan-AT-joeyta.local");
  200. attrs.put("mail","alang-AT-mail.joeyta-DOT-local");
  201. attrs.put("telephoneNumber","123 456 789");
  202. //some useful constants from lmaccess.h
  203. int UF_ACCOUNTDISABLE = 0x0002;
  204. int UF_PASSWD_NOTREQD = 0x0020;
  205. int UF_PASSWD_CANT_CHANGE = 0x0040;
  206. int UF_NORMAL_ACCOUNT = 0x0200;
  207. int UF_DONT_EXPIRE_PASSWD = 0x10000;
  208. int UF_PASSWORD_EXPIRED = 0x800000;
  209. //Note that you need to create the user object before you can
  210. //set the password. Therefore as the user is created with no
  211. //password, user AccountControl must be set to the following
  212. //otherwise the Win2K3 password filter will return error 53
  213. //unwilling to perform.
  214. attrs.put("userAccountControl",Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_PASSWORD_EXPIRED+ UF_ACCOUNTDISABLE));
  215. // Create the context
  216. Context result = ctx.createSubcontext(sUserName, attrs);
  217. System.out.println("Created disabled account for: " + sUserName);
  218. //now that we've created the user object, we can set the
  219. //password and change the userAccountControl
  220. //and because password can only be set using SSL/TLS
  221. //lets use StartTLS
  222. //StartTlsResponse tls = (StartTlsResponse)ctx.extendedOperation(new StartTlsRequest());
  223. //tls.negotiate();
  224. //set password is a ldap modfy operation
  225. //and we'll update the userAccountControl
  226. //enabling the acount and force the user to update ther password
  227. //the first time they login
  228. ModificationItem[] mods = new ModificationItem[2];
  229. //Replace the "unicdodePwd" attribute with a new value
  230. //Password must be both Unicode and a quoted string
  231. String newQuotedPassword = "\"P-AT-ssw0rd\"";
  232. byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
  233. mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
  234. mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl",Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWORD_EXPIRED)));
  235. // Perform the update
  236. ctx.modifyAttributes(sUserName, mods);
  237. System.out.println("Set password & updated userccountControl");
  238. //now add the user to a group.
  239. try {
  240. ModificationItem member[] = new ModificationItem[1];
  241. member[0]= new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("member", sUserName));
  242. ctx.modifyAttributes(sGroupName,member);
  243. System.out.println("Added user to group: " + sGroupName);
  244. }
  245. catch (NamingException e) {
  246. System.err.println("Problem adding user to group: " + e);
  247. }
  248. //Could have put tls.close() prior to the group modification
  249. //but it seems to screw up the connection or context ?
  250. //tls.close();
  251. System.out.println("Successfully created User: " + sUserName);
  252. return true;
  253. }
  254. catch (NamingException e) {
  255. System.err.println("Problem creating object: " + e);
  256. }
  257. catch (IOException e) {
  258. System.err.println("Problem creating object: " + e);
  259. }
  260. return false;
  261. }
  262. public boolean addUserToGroup(LdapContext ctx, String userDN, String groupDN) {
  263. try{
  264. ModificationItem[] mods = new ModificationItem[1];
  265. mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("member", userDN));
  266. ctx.modifyAttributes(groupDN, mods);
  267. System.out.println("Added user " + userDN + " to group " + groupDN);
  268. return true;
  269. } catch (NamingException ne){
  270. System.err.println("Problem add user to group: " + ne);
  271. }
  272. return false;
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP