java 域账户_Java访问域账号Ldap登录

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---------------");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值