code_junkie

Authenticating against Active Directory with Java on Linux

Nov 13th, 2011
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.65 KB | None | 0 0
  1. import com.sun.jndi.ldap.LdapCtxFactory;
  2. import java.util.ArrayList;
  3. import java.util.Hashtable;
  4. import java.util.List;
  5. import java.util.Iterator;
  6. import javax.naming.Context;
  7. import javax.naming.AuthenticationException;
  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.DirContext;
  13. import javax.naming.directory.SearchControls;
  14. import javax.naming.directory.SearchResult;
  15. import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;
  16.  
  17. //import org.acegisecurity.AuthenticationException;
  18. import org.acegisecurity.BadCredentialsException;
  19. import org.acegisecurity.GrantedAuthority;
  20. import org.acegisecurity.GrantedAuthorityImpl;
  21. import org.acegisecurity.providers.AuthenticationProvider;
  22. import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
  23. import org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider;
  24. import org.acegisecurity.userdetails.UserDetails;
  25. import org.acegisecurity.userdetails.UserDetailsService;
  26. import org.acegisecurity.userdetails.UsernameNotFoundException;
  27.  
  28.  
  29. class App2 {
  30.  
  31. public static void main(String[] args) {
  32.  
  33. if (args.length != 4 && args.length != 2) {
  34. System.out.println("Purpose: authenticate user against Active Directory and list group membership.");
  35. System.out.println("Usage: App2 <username> <password> <domain> <server>");
  36. System.out.println("Short usage: App2 <username> <password>");
  37. System.out.println("(short usage assumes 'xyz.tld' as domain and 'abc' as server)");
  38. System.exit(1);
  39. }
  40.  
  41. String domainName;
  42. String serverName;
  43.  
  44. if (args.length == 4)
  45. {
  46. domainName = args[2];
  47. serverName = args[3];
  48. }
  49. else
  50. {
  51. domainName = "xyz.tld";
  52. serverName = "abc";
  53. }
  54.  
  55. String username = args[0];
  56. String password = args[1];
  57.  
  58. System.out.println("Authenticating " + username + "@" + domainName + " through " + serverName + "." + domainName);
  59.  
  60. // bind by using the specified username/password
  61. Hashtable props = new Hashtable();
  62. String principalName = username + "@" + domainName;
  63. props.put(Context.SECURITY_PRINCIPAL, principalName);
  64. props.put(Context.SECURITY_CREDENTIALS, password);
  65. DirContext context;
  66.  
  67. try {
  68. context = LdapCtxFactory.getLdapCtxInstance("ldap://" + serverName + "." + domainName + '/', props);
  69. System.out.println("Authentication succeeded!");
  70.  
  71. // locate this user's record
  72. SearchControls controls = new SearchControls();
  73. controls.setSearchScope(SUBTREE_SCOPE);
  74. NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls);
  75. if(!renum.hasMore()) {
  76. System.out.println("Cannot locate user information for " + username);
  77. System.exit(1);
  78. }
  79. SearchResult result = renum.next();
  80.  
  81. List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
  82. Attribute memberOf = result.getAttributes().get("memberOf");
  83. if(memberOf!=null) {// null if this user belongs to no group at all
  84. for(int i=0; i<memberOf.size(); i++) {
  85. Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"});
  86. Attribute att = atts.get("CN");
  87. groups.add(new GrantedAuthorityImpl(att.get().toString()));
  88. }
  89. }
  90.  
  91. context.close();
  92.  
  93. System.out.println();
  94. System.out.println("User belongs to: ");
  95. Iterator ig = groups.iterator();
  96. while (ig.hasNext()) {
  97. System.out.println(" " + ig.next().toString());
  98. }
  99.  
  100. } catch (AuthenticationException a) {
  101. System.out.println("Authentication failed: " + a);
  102. System.exit(1);
  103. } catch (NamingException e) {
  104. System.out.println("Failed to bind to LDAP / get account information: " + e);
  105. System.exit(1);
  106. }
  107. }
  108.  
  109. private static String toDC(String domainName) {
  110. StringBuilder buf = new StringBuilder();
  111. for (String token : domainName.split("\.")) {
  112. if(token.length()==0) continue; // defensive check
  113. if(buf.length()>0) buf.append(",");
  114. buf.append("DC=").append(token);
  115. }
  116. return buf.toString();
  117. }
  118.  
  119. }
  120.  
  121. LDAPConnection connection = new LDAPConnection( new LDAPJSSEStartTLSFactory() );
  122. connection.connect(hostname, port);
  123. connection.startTLS();
  124. connection.bind(LDAPConnection.LDAP_V3, username+"@"+domain, password.getBytes());
Add Comment
Please, Sign In to add comment