今天主要实验了下用户的登陆验证,在PersonDaoImpl类中增长了验证方法java
具体代码:仍是PersonDaoImpl类app
1. public class PersonDaoImpl implements PersonDao { 2. 3. private LdapTemplate ldapTemplate; 4. 5. public static void main(String[] args) { 6. ApplicationContext cxt = new ClassPathXmlApplicationContext( 7. "applicationContext.xml"); 8. PersonDaoImpl personDao = (PersonDaoImpl) cxt.getBean("personDao"); 9. 10. // List users = personDao.getAllPersonNames(); 11. // System.out.println(users.size()); 12. String userName = "10010a"; 13. String passWord = "2039729"; 14. String userDn = personDao.getDnForUser(userName); 15. System.out.println("userDn:" + userDn); 16. boolean bl=personDao.authenticate(userDn, passWord); 17. System.out.println("验证结果:" + bl); 18. 19. 20. 21. } 22. 23. /** 24. * 根据CN属性取得用户DN(固然你能够根据本身状况换成别的属性来操做) 25. * @param cn 26. * @return 27. */ 28. private String getDnForUser(String cn) { 29. EqualsFilter f = new EqualsFilter("cn", cn); 30. List result = ldapTemplate.search(DistinguishedName.EMPTY_PATH, f 31. .toString(), new AbstractContextMapper() { 32. protected Object doMapFromContext(DirContextOperations ctx) { 33. return ctx.getNameInNamespace(); 34. } 35. }); 36. if (result.size() != 1) { 37. throw new RuntimeException("User not found or not unique"); 38. } 39. return (String) result.get(0); 40. } 41. /** 42. * 根据用户名密码验证 43. * @param userDn 44. * @param credentials 45. * @return 46. */ 47. public boolean authenticate(String userDn, String credentials) { 48. DirContext ctx = null; 49. try { 50. ctx = ldapTemplate.getContextSource().getContext(userDn, 51. credentials); 52. return true; 53. } catch (Exception e) { 54. // Contextcreationfailed-authenticationdidnotsucceed 55. 56. return false; 57. } finally { 58. // ItisimperativethatthecreatedDirContextinstanceisalwaysclosed 59. LdapUtils.closeContext(ctx); 60. } 61. }
备注:咱们注意到在用用户名密码验证前,我先去目录中取到了它的DN,这是由于getContext方法中参数userDn必须是一个完整的全路径DN。不然它不知道去哪找这个用户,并且登陆的用户也不必定都统一放在一个目录路径下ui