Java访问域账号Ldap登录

配置

#ldap
ldap:
  host: 10.10.10.000
  port: xxxx
  searchBase: DC=域节点,DC=site #  搜索域节点
  searchFilter: xxxxxx #  搜索的属性
  suffix: "@XXXXX.site" #  域账号后缀

Java代码

package com.java.basic.service.impl;

import com.java.dto.ResultMsg;
import com.java.utils.EmptyUtils;
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Created by lu.xu on 2018/6/20. TODO:ladp登录
 */
@Component
public class LdapLoginServiceImpl {

  private static final Logger logger = LoggerFactory.getLogger(LdapLoginServiceImpl.class);

  @Value("${ldap.host}")
  private String ldapHost;

  @Value("${ldap.port}")
  private String ldapPort;

  @Value("${ldap.searchBase}")
  private String ldapSearchBase;

  @Value("${ldap.searchFilter}")
  private String ldapSearchFilter;

  @Value("${ldap.suffix}")
  private String ldapSuffix;

  /**
   * TODO:LDAP登录入口
   *
   * @param userName ldap用户名
   * @param pwd ldap密码
   */
  public ResultMsg ldapLogin(String userName, String pwd) {
    logger.info(">>ldap-登录开始..");
    if (EmptyUtils.isAnyEmpty(ldapHost, ldapPort, ldapSearchBase, ldapSearchFilter, ldapSuffix)) {
      logger
          .error(
              "ldap-登录失败,ldap配置异常;ldapHost:{}, ldapPort:{}, ldapSearchBase:{}, ldapSearchFilter:{}, ldapSuffix:{}",
              ldapHost, ldapPort, ldapSearchBase, ldapSearchFilter, ldapSuffix);
      return new ResultMsg(false, "ldap登录失败,ldap配置异常");
    }
    final String ldapURL = "ldap://" + ldapHost + ":" + ldapPort;
    if (!userName.endsWith(ldapSuffix)) {
      userName += ldapSuffix;
    }
    logger.info("{} access ldap :{} ", userName, ldapURL);
    Hashtable env = new Hashtable();
    DirContext ctx = null;
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userName);
    env.put(Context.SECURITY_CREDENTIALS, pwd);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapURL);

    /**ldap登录,如果有异常说明登录失败*/
    try {
      ctx = new InitialDirContext(env);
      String searchBase = ldapSearchBase;
      String searchFilter =
          ldapSearchFilter + "=" + userName.substring(0, userName.indexOf(ldapSuffix));
      /** 定制返回属性,不定制属性,将返回所有的属性集*/
      String returnedAtts[] =
          {"mail", "pager", "company", "name", "displayName", "sAMAccountName", "telephoneNumber",
              "mobile"};
      SearchControls searchCtls = new SearchControls();
      searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
      searchCtls.setReturningAttributes(returnedAtts);
      NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

      int searchIndex = 0;
      String userWorkId = null;
      String userEmail = null;
      String userdisplayName = null;
      String userTelephoneNumber = null;

      while (answer.hasMoreElements()) {
        if (searchIndex == 1) {
          logger.error("查询出多个相同的ldap账号:" + userName);
          return new ResultMsg(false, "查询出多个相同的域账号:" + userName);
        }
        SearchResult sr = (SearchResult) answer.next();
        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
          /**调试,输出属性信息*/
          this.printLdapAttribute(attrs);

          Attribute userWorkIdAtt = attrs.get("pager");
          Attribute userEmailAtt = attrs.get("mail");
          Attribute userDisplayNameAtt = attrs.get("displayName");
          Attribute telephoneNumberAtt = attrs.get("telephoneNumber");
          /**获取查询的属性值*/
          userWorkId = userWorkIdAtt.getAll().next().toString();
          userEmail = userEmailAtt.getAll().next().toString();
          userdisplayName = userDisplayNameAtt.getAll().next().toString();
          userTelephoneNumber = telephoneNumberAtt.getAll().next().toString();
        }
        searchIndex++;
      }
      return new ResultMsg(true, "ldap登录成功");
    } catch (AuthenticationException e) {
      return new ResultMsg(false, "域登录身份验证失败");
    } catch (javax.naming.CommunicationException e) {
      return new ResultMsg(false, "ldap域连接失败");
    } catch (Exception err) {
      err.printStackTrace();
      return new ResultMsg(false, "异常信息未知");
    } finally {
      if (null != ctx) {
        try {
          ctx.close();
        } catch (Exception e) {
          logger.error("InitialDirContext 关闭异常..");
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * ldap调试,输出属性
   */
  private void printLdapAttribute(Attributes attrs) throws Exception {
    if (null == attrs) {
      throw new RuntimeException("ldap-Attributes can not be null");
    }
    System.out.println("--------------ldap-Attributes-start---------------");
    for (NamingEnumeration ne = attrs.getAll(); ne.hasMore(); ) {
      Attribute attr = (Attribute) ne.next();
      String attributeID = attr.getID().toString();
      System.out.println("\nAttributeID:" + attributeID);
      for (NamingEnumeration e = attr.getAll(); e.hasMore(); ) {
        String attributeValue = e.next().toString();
        System.out.println("  attributeValue:" + attributeValue);
      }
    }
    System.out.println("--------------ldap-Attributes-end---------------");
  }

}

转载于:https://my.oschina.net/u/3457546/blog/1919594

你可能感兴趣的:(Java访问域账号Ldap登录)