1.创建连接
/**
* 获取连接
* @param type 操作类型:1.操作用户2.操作用户组
* @return
*/
private static LdapContext getConnection(int type) {
LdapContext ctx = null;
Hashtable<String, String> env = new Hashtable<>();
StringBuffer ldapUrl = new StringBuffer();
if (type == 1) {// 对用户操作时
ldapUrl.append("ldap://127.0.0.1:389/").append("ou=Duser,dc=sss,dc=com");
} else if (type == 2) {// 对用户组操作时
ldapUrl.append("ldap://127.0.0.1:389/").append("ou=Group,dc=sss,dc=com");
}
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LadpCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "uid=ldap,ou=aaa,dc=sss,dc=com");// 用户名
env.put(Context.SECURITY_CREDENTIALS, "psw12345t");// 密码
env.put(Context.PROVIDER_URL, ldapUrl.toString());// 目录地址
try {
ctx = new InitialLdapContext(env, null);// 创建连接
} catch (NamingException e) {
e.printStackTrace();
return null;
}
return ctx;
}
2.新增用户
/**
* 新增用户---注意密码部分--{加密类型}加密后的密码
* @param userId
* @return
*/
public static boolean addUser(String userId) {
// 创建连接,此时的目录地址是ou=Duser,dc=sss,dc=com,创建的用户会存在这底下
LdapContext ctx = getConnection(1);
if (ctx != null) {
try {
BasicAttributes attrsbus = new BasicAttributes();
BasicAttribute objClass = new BasicAttribute("objectclass");
objClass.add("inetOrgPerson");
objClass.add("posixAccount");
objClass.add("top");
objClass.add("shadowAccount");
attrsbus.put(objClass);
attrsbus.pu