上次写的程序存在很大的问题,就是子目录用户不能登录。所以我们要先通过用户cn获取到用户dn,然后再验证登录。
程序需要使用到jldap.jar 这个自己网上搜索下载。
获取DN的程序
- package ldap;
- import com.novell.ldap.LDAPConnection;
- import com.novell.ldap.LDAPEntry;
- import com.novell.ldap.LDAPException;
- import com.novell.ldap.LDAPSearchResults;
- public class getDN {
- public String getDN(String userName) {
- String ldaphost = "192.168.XX.XX";
- int ldapPort = LDAPConnection.DEFAULT_PORT;
- String searchBase = "dc=XX,dc=com";
- String searchFilter = "objectClass=*";
- int searchScope = LDAPConnection.SCOPE_SUB;
- LDAPConnection lc = new LDAPConnection();
- String dn = null;
- try {
- lc.connect(ldaphost, ldapPort);
- LDAPSearchResults searchResults = lc.search(searchBase,
- searchScope, searchFilter, null, false);
- while (searchResults.hasMore()) {
- LDAPEntry nextEntry = null;
- nextEntry = searchResults.next();
- String str = nextEntry.getDN();
- String str1 = "cn=" + userName + "";
- if (str.contains(str1)) {
- dn = str;
- return dn;
- }
- }
- } catch (LDAPException t) {
- dn=null;
- }
- return dn;
- }
- /* public static void main(String []args){
- getDN conn = new getDN();
- System.out.println(conn.getDN("test1"));
- }
- */
- }
验证登录
- public boolean login(String name,String password) {
- boolean result = true;
- getDN getdn = new getDN();
- String ldapdn=getdn.getDN(name);
- DirContext ctx = null;
- Hashtable<String, String> env = new Hashtable<String, String>();
- env.put(Context.INITIAL_CONTEXT_FACTORY,
- "com.sun.jndi.ldap.LdapCtxFactory");
- env.put(Context.PROVIDER_URL, host); // LDAP host
- env.put(Context.SECURITY_AUTHENTICATION, "simple"); // 简单模式进行连接
- env.put(Context.SECURITY_PRINCIPAL,ldapdn); // 用户名
- env.put(Context.SECURITY_CREDENTIALS, password); // 密码传进去
- try {
- ctx = new InitialDirContext(env);
- } catch (Exception e) {
- result = false;
- }
转载于:https://blog.51cto.com/zgssheng/976201