public class PersonDaoImpl implements PersonDao {
private LdapTemplate ldapTemplate;
public static void main(String[] args) {
ApplicationContext cxt = new ClassPathXmlApplicationContext(
"applicationContext.xml");
PersonDaoImpl personDao = (PersonDaoImpl) cxt.getBean("personDao");
// List users = personDao.getAllPersonNames();
// System.out.println(users.size());
String userName = "10010a";
String passWord = "2039729";
String userDn = personDao.getDnForUser(userName);
System.out.println("userDn:" + userDn);
boolean bl=personDao.authenticate(userDn, passWord);
System.out.println("验证结果:" + bl);
}
/**
* 根据CN属性取得用户DN(当然你可以根据自己情况换成别的属性来操作)
* @param cn
* @return
*/
private String getDnForUser(String cn) {
EqualsFilter f = new EqualsFilter("cn", cn);
List result = ldapTemplate.search(DistinguishedName.EMPTY_PATH, f
.toString(), new AbstractContextMapper() {
protected Object doMapFromContext(DirContextOperations ctx) {
return ctx.getNameInNamespace();
}
});
if (result.size() != 1) {
throw new RuntimeException("User not found or not unique");
}
return (String) result.get(0);
}
/**
* 根据用户名密码验证
* @param userDn
* @param credentials
* @return
*/
public boolean authenticate(String userDn, String credentials) {
DirContext ctx = null;
try {
ctx = ldapTemplate.getContextSource().getContext(userDn,
credentials);
return true;
} catch (Exception e) {
// Contextcreationfailed-authenticationdidnotsucceed
return false;
} finally {
// ItisimperativethatthecreatedDirContextinstanceisalwaysclosed
LdapUtils.closeContext(ctx);
}
}