1【仿写】
2
public LdapContext getLdapContext() throws NamingException {
String userName = "App01"; // 用户名称
String password = "password"; // 密码
String host = "192.168.1.1"; // AD服务器
String port = "389"; // 端口
String url = new String("ldap://" + host + ":" + port);
Hashtable env = new Hashtable();
env.put(Context.SECURITY_AUTHENTICATION, "simple");// 以simple方式发送
env.put(Context.SECURITY_PRINCIPAL,
"cn=App01,cn=users,DC=com"); //
env.put(Context.SECURITY_CREDENTIALS, password);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
return new InitialLdapContext(env, null);
}
3
public void add() {
try {
String newUserName = "test1";
BasicAttributes attrs = new BasicAttributes();
BasicAttribute objclassSet = new BasicAttribute("objectclass");
objclassSet.add("person");
objclassSet.add("top");
objclassSet.add("organizationalPerson");
objclassSet.add("user");
attrs.put(objclassSet);
attrs.put("sn", newUserName);
attrs.put("uid", newUserName);
attrs.put("cn", newUserName);
attrs.put("userPassword", "password");
attrs.put("sAMAccountName","test1");
attrs.put("userAccountControl","2");
attrs.put("mail",newUserName+"@163.com");
attrs.put("displayName","张三");
attrs.put("homePhone","666666");
attrs.put("telephoneNumber","13888888888");
attrs.put("title","Test1");
getLdapContext().createSubcontext("cn=" + newUserName + ",cn=users,DC=com", attrs);
} catch (Exception e) {
e.printStackTrace();
}
}
4
public void testModify() {
String uid = "test1";
String userDN = "cn=" + uid + ",cn=users,DC=com";
Attributes attrs = new BasicAttributes(true);
attrs.put("userPassword", "test2");
attrs.put("title", "Manager");
try {
getLdapContext().modifyAttributes(userDN, DirContext.REPLACE_ATTRIBUTE, attrs);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
5
public void removeUser(String userName){
try {
getLdapContext().destroySubcontext("cn=" + userName + ",cn=users,DC=com");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
6
public void search() {
SearchControls searchCtls = new SearchControls(); // Create the search
// controls
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Specify
String searchFilter = "(&(objectClass=user)(cn=test2))";//"(objectClass=user)";//
String[] returnedAtts = new String[] { "distinguishedName","userPassword",
"department","title","userPassword","sAMAccountName", "flags", "displayName","whenChanged" };
searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集
String searchBase = "DC=com";
NamingEnumeration<SearchResult> answer = null;
List<Map<String, String>> adList = new ArrayList<Map<String, String>>();
try {
answer = this.getLdapContext().search(searchBase, searchFilter,
searchCtls);
while (answer.hasMoreElements()) {
SearchResult searchResult = answer.next();
Attributes attributes = searchResult.getAttributes();
Map<String, String> accountInfo = new HashMap<String, String>();
for (NamingEnumeration<?> namingEnumeration = attributes
.getAll(); namingEnumeration.hasMore();) {
Attribute attribute = (Attribute) namingEnumeration.next();
String attrId = attribute.getID().toString();
attribute.getAttributeDefinition();
int i = 0;
String attrValue = "";
for (NamingEnumeration<?> e = attribute.getAll(); e
.hasMore();) {
String val = e.next().toString();
if (i != 0) {
attrValue += ";";
}
i++;
attrValue += val;
}
System.out.println("attrId:" + attrId+" attrValue:" + attrValue);
accountInfo.put(attrId, attrValue);
}
adList.add(accountInfo);
System.out.println("\n\n");
}
System.out.println("size:" + adList.size());
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("AD服务器域管理员账号验证失败!");
} catch (NamingException e) {
e.printStackTrace();
System.out.println("AD服务器连接失败,请检查配置是否正确!");
}
}
7 Spring Ldap
private LdapTemplate ldapTemplate;
public void setLdapTemplate(LdapTemplate ldapTemplate) {
this.ldapTemplate = ldapTemplate;
}
public void getAllUser() {
AndFilter andFilter = new AndFilter();
andFilter.and(new EqualsFilter("objectclass", "person"));
//andFilter.and(new EqualsFilter("cn", "xwl"));
List list = ldapTemplate.search("cn=users,DC=com", andFilter.encode(),
new UserAttributeMapper());
for(Object u:list){
System.out.println(((Users)u).getName());
System.out.println(((Users)u).getPwd()+"\n");
}
System.out.println(list.size());
}
public void bind1() {
BasicAttribute objclassSet = new BasicAttribute("objectclass");
objclassSet.add("person");
objclassSet.add("top");
objclassSet.add("organizationalPerson");
objclassSet.add("user");
Attributes attr = new BasicAttributes();
attr.put(objclassSet);
// 必填属性,不能为null也不能为空字符串
attr.put("sn", "test1");
attr.put("uid", "test1");
attr.put("cn", "xwl1");
attr.put("sAMAccountName", "test1");
attr.put("userPassword", "1qa2ws3ed54");
attr.put("userAccountControl", "2");
attr.put("mail", "test3@163.com");
ldapTemplate.bind(("cn=xwl1,cn=users,DC=com"), null, attr);
}
public static void main(String[] args) {
ApplicationContext cxt = new ClassPathXmlApplicationContext("app_ldap.xml");
LdapPersonInfoImpl userDao = (LdapPersonInfoImpl) cxt
.getBean("ldapPersonInfoImpl");
//List<String> users =
userDao.getAllUser();//getAllPersonNames();
// for(String str:users)
// System.out.println(str);
// userDao.bind1();
}
public class UserAttributeMapper implements AttributesMapper {
private Logger log=Logger.getLogger(UserAttributeMapper.class);
@Override
public Object mapFromAttributes(Attributes attr) throws NamingException {
Users user = new Users();
user.setName(attr.get("sAMAccountName").get().toString());
try {
user.setPwd(new String((byte[])attr.get(LdapContextSourceBean.AD_USER_PASS_WORD).get(), "GB2312"));
} catch (Exception e) {
log.error(" User Passwrod get fail",e);
}
return user;
}
}
8
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource"> <property name="url" value="ldap://192.168.1.1:389" /> <property name="userDn" value="cn=App01,cn=users,DC=com" /> <property name="password" value="password" /> </bean> <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate"> <constructor-arg ref="contextSource" /> </bean> <bean id="ldapPersonInfoImpl" class="com.ladp.LdapPersonInfoImpl"> <property name="ldapTemplate"> <ref bean="ldapTemplate" /> </property> </bean> </beans>
spring-ldap-core-1.3.2.RELEASE.jar
9
10