对身份验证在Linux上使用Java的Active Directory [英] Authenticating against Active Directory with Java on Linux
问题描述
我对使用Java的Active Directory进行身份验证的一个简单的任务。只是验证凭证,别无其他。比方说,我的域名是fun.xyz.tld,OU路径是未知的,用户名/密码是testu / testp。
I have a simple task of authenticating against Active Directory using Java. Just verifying credentials and nothing else. Let's say my domain is "fun.xyz.tld", OU path is unknown, and username/password is testu/testp.
我知道有几个Java库在那里,简化了这项任务,但我没有成功地实现它们。我发现大多数的例子涉及的LDAP一般,没有特别的Active Directory。发出LDAP请求是指发送一个OU路径是,我没有。此外,发出LDAP请求的应用应该已经被绑定到Active Directory才能访问它...不安全,因为凭据必须被存放在某处发现。我想测试绑定与检验凭证,如果可能的话 - 这将意味着帐户是有效的
I know there's a few Java libraries out there that simplify this task, but I wasn't successful at implementing them. Most examples that I've found addressed LDAP in general, not specifically Active Directory. Issuing LDAP request means sending an OU path in it, which I don't have. Also, the application that issues LDAP request should be already bound to Active Directory in order to access it... Insecure, since the credentials would have to be stored someplace discoverable. I would like a test bind with test credentials, if possible - this would mean that account is valid.
最后,如果可能的话,有没有一种方法,使这种认证机制加密?我知道,公元使用Kerberos,但不知道Java的LDAP方法做的。
Last, if possible, is there a way to make such authentication mechanism encrypted? I know that AD uses Kerberos, but not sure if Java's LDAP methods do.
有没有人有工作code的例子吗?谢谢你。
Does anyone has an example of working code? Thanks.
推荐答案
这里的code我放在一起的基础上例如,从本博客的链接将该源:<一href="http://fisheye4.atlassian.com/browse/hudson/trunk/hudson/plugins/active-directory/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java"相对=nofollow>链接。
Here's the code I put together based on example from this blog: LINK and this source: LINK.
import com.sun.jndi.ldap.LdapCtxFactory;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.AuthenticationException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;
//import org.acegisecurity.AuthenticationException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.providers.AuthenticationProvider;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
class App2 {
public static void main(String[] args) {
if (args.length != 4 && args.length != 2) {
System.out.println("Purpose: authenticate user against Active Directory and list group membership.");
System.out.println("Usage: App2 <username> <password> <domain> <server>");
System.out.println("Short usage: App2 <username> <password>");
System.out.println("(short usage assumes 'xyz.tld' as domain and 'abc' as server)");
System.exit(1);
}
String domainName;
String serverName;
if (args.length == 4) {
domainName = args[2];
serverName = args[3];
} else {
domainName = "xyz.tld";
serverName = "abc";
}
String username = args[0];
String password = args[1];
System.out
.println("Authenticating " + username + "@" + domainName + " through " + serverName + "." + domainName);
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + "@" + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS, password);
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance("ldap://" + serverName + "." + domainName + '/', props);
System.out.println("Authentication succeeded!");
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),
"(& (userPrincipalName=" + principalName + ")(objectClass=user))", controls);
if (!renum.hasMore()) {
System.out.println("Cannot locate user information for " + username);
System.exit(1);
}
SearchResult result = renum.next();
List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
Attribute memberOf = result.getAttributes().get("memberOf");
if (memberOf != null) {// null if this user belongs to no group at all
for (int i = 0; i < memberOf.size(); i++) {
Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" });
Attribute att = atts.get("CN");
groups.add(new GrantedAuthorityImpl(att.get().toString()));
}
}
context.close();
System.out.println();
System.out.println("User belongs to: ");
Iterator ig = groups.iterator();
while (ig.hasNext()) {
System.out.println(" " + ig.next().toString());
}
} catch (AuthenticationException a) {
System.out.println("Authentication failed: " + a);
System.exit(1);
} catch (NamingException e) {
System.out.println("Failed to bind to LDAP / get account information: " + e);
System.exit(1);
}
}
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if (token.length() == 0)
continue; // defensive check
if (buf.length() > 0)
buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
}
这篇关于对身份验证在Linux上使用Java的Active Directory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!