SpringLDAP 简单的用户登陆认证

今天主要实验了下用户的登录验证,在PersonDaoImpl类中增加了验证方法

具体代码:还是PersonDaoImpl类

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。否则它不知道去哪找这个用户,而且登录的用户也不一定都统一放在一个目录路径下

你可能感兴趣的:(exception,String,list,object,Class,credentials)