import java.util.List;
import java.util.Map;
/**
* LDAP服务接口
* @author guoming
*
*/
public interface LDAPServiceI {
/**
* 验证指定的用户是否存在<br/>
* @param userName 用户名
* @return
*/
public boolean verifyUserExists(String userName);
/**
* 验证用户
*
* @param userDn 用户名
* @param password 用户密码
* @return 验证是否成功
*/
public boolean authUser(String userName, String password);
/**
* 获取指定DN下的所有用户名称列表<br/>
* @param DN
* @return 用户名称列表
*/
public List<String> getAllUserNameList();
/**
* 增加用户
* @param uid 用户名
* @param pwd 用户密码:如果密码没有值,则表示无密码
* @return map键值:{uid:xxxx,success:boolean,msg:reason}
*/
Map<String,Object> addUser(String uid,String pwd);
/**
* 删除用户
* @param uid 用户名
* @return
*/
boolean delUser(String uid);
/**
* 修改指定用户密码
* @param uid 用户名
* @param originalPwd 用户原始密码
* @param newPwd 用户新密码
* @return
*/
boolean modifyPwd(String uid,String originalPwd,String newPwd);
}
package com.alan;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import com.unboundid.ldap.sdk.Attribute;
import com.unboundid.ldap.sdk.Filter;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.LDAPSearchException;
import com.unboundid.ldap.sdk.Modification;
import com.unboundid.ldap.sdk.ModificationType;
import com.unboundid.ldap.sdk.SearchRequest;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SearchScope;
import com.unboundid.util.Base64;
/**
* LDAP服务实现类
* @author guoming
*
*/
public class LDAPServiceImpl implements LDAPServiceI {
private static String ldapHost="10.0.31.58";
private static int ldapPort=10389;
private static LDAPConnection connection = null;
private static String baseDN="ou=system";
private static String ldapPassword="secret";
/**
* 连接LDAP
*/
private static void openConnection(){
if (null == connection) {
try {
connection = new LDAPConnection(ldapHost,ldapPort,"uid=admin,"+baseDN,ldapPassword);
System.out.println(connection);
} catch (LDAPException e) {
System.out.println("connection ldap occurs error:\n"+e.getMessage());
}
}
}
static{
openConnection();
}
public static void main(String[] args)throws Exception {
LDAPServiceImpl service = new LDAPServiceImpl();
//System.out.println(service.addUser("tiao",""));
//System.out.println(service.delUser("baiy"));
System.out.println(service.authUser("tiao","111111"));
//System.out.println(service.modifyPwd("tiao","123456","111111"));
// List<String> resultList = service.getAllUserNameList();
// for (String name:resultList) {
// System.out.println("--->"+name);
// }
// if (service.verifyUserExists(userName)) {
//
// System.out.println(service.authUser(userName,pwd));
// }else{
//
// System.out.println(userName+" not exists!");
// }
}
@Override
public boolean verifyUserExists(String userName) {
Assert.notNull(userName,"user name can't be null!");
boolean flag = false;// 默认用户不存在
Filter filter = Filter.createEqualityFilter("uid",userName);
SearchRequest searchRequest = new SearchRequest(baseDN,SearchScope.SUB,filter);
SearchResult searchResult = null;
try {
searchResult=connection.search(searchRequest);
if (null != searchResult && searchResult.getEntryCount()>0) {
flag = true;
}
} catch (LDAPSearchException e) {
System.out.println("query occurs error:\n"+e.getMessage());
}
return flag;
}
@Override
public boolean authUser(String userName, String password) {
boolean authResult = false;
Assert.notNull(userName,"user name can't be null!");
Filter filter = Filter.createEqualityFilter("uid",userName);
SearchRequest searchRequest = new SearchRequest(baseDN,SearchScope.ONE,filter);
SearchResult searchResult = null;
try {
searchResult=connection.search(searchRequest);
if (null != searchResult && searchResult.getEntryCount()>0) {
SearchResultEntry entry = searchResult.getSearchEntries().get(0);
authResult = this.verifyPwdEquality(entry, password);
}
} catch (LDAPSearchException e) {
System.out.println("query occurs error:\n"+e.getMessage());
}
return authResult;
}
/**
* 验证密码的一致性
* @param entry
* @param password 用户输入的密码
* @return
*/
private boolean verifyPwdEquality(SearchResultEntry entry,String password) {
Assert.notNull(entry, "entry can't be empty");
boolean authResult = false;
String oldPwd = entry.getAttributeValue("userPassword");
if (!StringUtils.hasLength(password) && !StringUtils.hasLength(oldPwd)) {// 如果不存在userPassword属性,前password为空则返回true
authResult = true;
return authResult;
}
if (StringUtils.hasLength(password) && (StringUtils.hasLength(oldPwd))){
String algorithmStr = "";
if (oldPwd.contains("{SHA}") || oldPwd.contains("{SSHA}")
|| oldPwd.contains("{sha}") || oldPwd.contains("{ssha}")) {// 使用sha-1算法对新旧密码进行比较
algorithmStr = "sha-1";
}else if(oldPwd.contains("{md5}") || oldPwd.contains("{MD5}")) {// 使用md5算法对新旧密码进行比较
algorithmStr = "md5";
}
try {
authResult = verifySHA(algorithmStr,oldPwd,password);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return authResult;
}
/**
* 验证密码是否一致
* @param algorithm 算法名称
* @param ldappw ldap中的密码
* @param inputpw 用户输入的密码
* @return
* @throws NoSuchAlgorithmException
*/
public static boolean verifySHA(String algorithm,String ldappw, String inputpw)
throws NoSuchAlgorithmException {
// MessageDigest 提供了消息摘要算法,如 MD5 或 SHA,的功能,这里LDAP使用的是SHA-1
if (!StringUtils.hasLength(algorithm)) {
algorithm="sha-1";
}
MessageDigest md = MessageDigest.getInstance(algorithm);
// 取出加密字符
if (ldappw.startsWith("{ssha}") || ldappw.startsWith("{SSHA}")) {
ldappw = ldappw.substring(6);
} else if (ldappw.startsWith("{sha}") || ldappw.startsWith("{SHA}") || ldappw.startsWith("{MD5}")
|| ldappw.startsWith("{md5}")) {
ldappw = ldappw.substring(5);
}
// 解码BASE64
byte[] ldappwbyte=null;
try {
ldappwbyte = Base64.decode(ldappw);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] shacode;
byte[] salt;
// 前20位是SHA-1加密段,20位后是最初加密时的随机明文
if (ldappwbyte.length <= 20) {
shacode = ldappwbyte;
salt = new byte[0];
} else {
shacode = new byte[20];
salt = new byte[ldappwbyte.length - 20];
System.arraycopy(ldappwbyte, 0, shacode, 0, 20);
System.arraycopy(ldappwbyte, 20, salt, 0, salt.length);
}
// 把用户输入的密码添加到摘要计算信息
md.update(inputpw.getBytes());
// 把随机明文添加到摘要计算信息
md.update(salt);
// 按SSHA把当前用户密码进行计算
byte[] inputpwbyte = md.digest();
// 返回校验结果
return MessageDigest.isEqual(shacode, inputpwbyte);
}
@Override
public List<String> getAllUserNameList() {
List<String> resultList = new ArrayList<String>();
Filter filter = Filter.createEqualityFilter("objectClass","person");
SearchRequest searchRequest = new SearchRequest(baseDN,SearchScope.ONE,filter);
SearchResult searchResult = null;
try {
searchResult=connection.search(searchRequest);
if (null != searchResult && searchResult.getEntryCount()>0) {
for (SearchResultEntry entry : searchResult.getSearchEntries()) {
resultList.add(entry.getAttributeValue("uid"));
}
}
} catch (LDAPSearchException e) {
e.printStackTrace();
}
return resultList;
}
@Override
public Map<String,Object> addUser(String uid, String pwd) {
Assert.hasLength(uid,"uid can't be empty");
Map<String,Object> so = new HashMap<String,Object>();
so.put("uid","");
so.put("success",false);
so.put("msg","");
if(this.verifyUserExists(uid)){// 说明用户已存在
so.put("uid",uid);
so.put("success",false);
so.put("msg",uid+" have exists!");
return so;
}
List<Attribute> attributes = new ArrayList<Attribute>();
attributes.add(new Attribute("objectClass","organizationalPerson","person","inetOrgPerson","top"));
attributes.add(new Attribute("sn","person"));
attributes.add(new Attribute("cn","person"));
attributes.add(new Attribute("uid",uid));
if (StringUtils.hasLength(pwd)) {
attributes.add(new Attribute("userPassword",pwd));
}
try {
connection.add("uid="+uid+","+baseDN, attributes);
so.put("uid",uid);
so.put("success",true);
so.put("msg","");
} catch (LDAPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return so;
}
@Override
public boolean delUser(String uid) {
Assert.hasLength(uid,"uid can't be empty");
boolean flag = true;
if (this.verifyUserExists(uid)) {
try {
connection.delete("uid="+uid+","+baseDN);
} catch (LDAPException e) {
flag = false;
e.printStackTrace();
}
}
return flag;
}
@Override
public boolean modifyPwd(String uid, String originalPwd,String newPwd) {
Assert.hasLength(uid,"uid can't be empty");
Assert.hasLength(newPwd,"new pwd can't be empty");
boolean flag = false;
/***************第一步 首先取出指定用户的旧密码**********************/
String filter = "(&(objectclass=person)(uid="+uid+"))";
try {
SearchRequest searchRequest = new SearchRequest(baseDN,SearchScope.ONE,filter);
SearchResult searchResult = null;
searchResult=connection.search(searchRequest);
SearchResultEntry entry= null;
if (null != searchResult && searchResult.getEntryCount()>0) {
entry = searchResult.getSearchEntries().get(0);
}
/***************第二步 验证输入的旧密码是否与LDAP服务器上的旧密码一致**********************/
boolean authResult = false;
if (null != entry) {
authResult = this.verifyPwdEquality(entry, originalPwd);
}
System.out.println("authResult="+authResult);
Modification modification = null;
String exists="";
if (authResult) {// 说明旧密码认证通过,则修改新的密码
exists = entry.getAttributeValue("userPassword");
modification = new Modification(ModificationType.ADD,"userPassword",newPwd);
if (StringUtils.hasLength(exists)) {// 则进行替换
modification = new Modification(ModificationType.REPLACE,"userPassword",newPwd);
}
connection.modify("uid="+uid+","+baseDN, modification);
flag = true;
}
} catch (LDAPException e) {
e.printStackTrace();
}
return flag;
}
}