今天主要實驗了下用戶的登陸驗證,在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