.net 或java中操作AD域

1、C# 版

        [HttpGet]
        public OALoginResultVO userLogin()
        {
            OALoginResultVO _oALoginResultVO = new OALoginResultVO();
            try
            {
                string loginName = "test";
                string pwd = "*********";
                //域服务器地址
                object LDAPAddress = ConfigurationManager.AppSettings["LDAPAddesss"];
                //1、验证域账号是否匹配
                DirectoryEntry _directoryEntry = new DirectoryEntry(LDAPAddress.ToString(), loginName, pwd);
                DirectorySearcher _search = new DirectorySearcher(_directoryEntry);
                _search.Filter = "(&(objectCategory=Person)(objectClass=User)(SAMAccountName=" + loginName + "))";
                _search.PropertiesToLoad.Add("cn");
                SearchResult _searchResult = _search.FindOne();
                _oALoginResultVO.token = "";
            }
            catch (Exception ex)
            {
                _oALoginResultVO.code = -1;
                _oALoginResultVO.token = "";
                //写入日志

            }
            return _oALoginResultVO;
        }

 

 

 

2、java 版

 

 

import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

具体方法实现如下:     

/**
	 * desc:域服务器地址
	 * */
    @Value("${systemsettings.LDAPAddress}")
	private String LDAPAddress="aspire.aspire-tech.com";
    /**
     * desc:解密私钥
     * */
    @Value("${systemsettings.PRIVATE_KEY}")
	private String PRIVATE_KEY;
	/**
	 * desc:OA域账号切换
	 **/
	@PostMapping(value = "/login/userLogin")
	public ViewOrgUser_All userLogin(@RequestBody OAUserInfoVO _OAUserInfoVO, HttpServletRequest _request) {
		LoginLog_Update _LoginLog_Update = new LoginLog_Update();
		//OALoginResultVO _OALoginResultVO = new OALoginResultVO();
		ViewOrgUser_All _ViewOrgUser_All=new ViewOrgUser_All();
		_ViewOrgUser_All.setSysExceptionCode("21");
		_ViewOrgUser_All.setSysExceptionDesc("登录失败,没有找到用户数据");
		List<ViewOrgUser_All> _list=new ArrayList<>();
		String userName="";
		DirContext ctx = null;
		try {
			
			//String root=":389/OU=shenzhen,DC=aspire,DC=aspire-tech,DC=com";
			//String host = LDAPAddress;
			String host = "10.10.10.10";
			String domain="10.10.10.10";
			String originalLoginname =_common.getUserLoginNameBytoken(_OAUserInfoVO.getParam1());
		    userName = _OAUserInfoVO.getParam2();
		    logger.info("userLogin start ,用户:"+userName);
			String password =RSACoder.decrypt(_OAUserInfoVO.getParam3(),PRIVATE_KEY);
			_LoginLog_Update.setOriginalLoginname(originalLoginname);
			_LoginLog_Update.setLoginname(userName);
			_LoginLog_Update.setClientIp(_request!=null?_common.getIpAddr(_request):"");
			if (userName.length()> 0 && password.length() > 0) {
				String LDAPAddress = new String("LDAP://" + host);
				String user = userName.indexOf(domain) > 0 ? userName : userName + "@" + domain;
				Hashtable env = new Hashtable();// 实例化一个Env
				env.put(Context.SECURITY_AUTHENTICATION, "simple");// LDAP访问安全级别(none,simple,strong),一种模式
				
				env.put(Context.SECURITY_PRINCIPAL, user); // 用户名
				env.put(Context.SECURITY_CREDENTIALS, password);// 密码
				env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");// LDAP工厂类
				env.put(Context.PROVIDER_URL, LDAPAddress);// Url
				logger.info("---------开始连接域控服务器,用户:"+userName);
				ctx = new InitialDirContext(env);// 初始化上下文
				logger.info("---------连接域控服务器成功,用户:"+userName);
				//_OALoginResultVO.setCode(0);
				//String token = "";
				// 查询用户token
				//token=_common.getTokenByUserLoginName(userName);
				Map<String, Object> _sqlWhereMap = new HashMap<String, Object>();
				_sqlWhereMap.put("userLoginName", userName);
				_list=_SApiViewOrgUser.ReadCustomAll(_sqlWhereMap);
				if(_list!=null&&_list.size()>0&&_list.get(0).getSysExceptionCode().equals("0")) {
					_ViewOrgUser_All=_list.get(0);
					_LoginLog_Update.setLogType("success");
					_LoginLog_Update.setLogTxt("登录成功");
					logger.info("用户:"+userName+",success");
				}else if(_list!=null&&_list.size()>0&&_list.get(0).getSysExceptionCode().equals("-1")){
					_LoginLog_Update.setLogType("failure");
					_LoginLog_Update.setLogTxt("获取用户token失败,Message :"+_list.get(0).getSysExceptionDesc());
				}
				

				
			} else {
				_LoginLog_Update.setLogType("failure");
				_LoginLog_Update.setLogTxt("用户名或密码不可以为空");
			}
		} catch (AuthenticationException e) {
			_LoginLog_Update.setLogType("failure");
			_LoginLog_Update.setLogTxt("用户名或密码不正确,Message:" + e.getMessage() + ",---" + e.getCause()+",---"+e.getStackTrace()+",---"+e.getExplanation());
			logger.info("---------连接域控服务器失败,用户:"+userName+",异常信息:"+e.getMessage()+","+e.getCause());
		} catch (javax.naming.CommunicationException e) {
			_LoginLog_Update.setLogType("failure");
			_LoginLog_Update.setLogTxt("用户名或密码不正确,Message:" + e.getMessage() + ",---" + e.getCause()+",---"+e.getStackTrace()+",---"+e.getExplanation());
			logger.info("---------连接域控服务器失败,用户:"+userName+",异常信息:"+e.getMessage()+","+e.getCause());
		} catch (Exception e) {
			_LoginLog_Update.setLogType("error");
			_LoginLog_Update.setLogTxt("服务器执行错误,Message:" + e.getMessage() + ",---" + e.getCause()+",---"+e.getStackTrace());
			logger.info("用户:"+userName+",failure");
		} finally {
			if (null != ctx) {
				try {
					ctx.close();
					ctx = null;
				} catch (Exception e) {
					// e.printStackTrace();
				}
			}
		}
		// 写入系统日志
		try {
			_SApiLoginLog.CreateBase(_LoginLog_Update);
		} catch (Exception e) {
			logger.error("服务器执行错误,Message:" + e.getMessage() + ",cause:" + e.getCause());
		}
		logger.info("userLogin end ,用户:"+userName);
		//return _OALoginResultVO;
		return _ViewOrgUser_All;
	}

java版代码详细说明:

1)、java在作AD域用户认证,域账号需要加上 域控制器域名,中间使用“@”或“\”都可以,C#版不需要

 

 

3、AD域认证常见错误及详细解决方法

(1)、java.net.ConnectException: Connection timed out (Connection timed out)

(2)、java.net.ConnectException: Connection refused (Connection refused)

以上两种错误尝试关闭360黑客入侵防护可解决,如下图

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大海中一粒沙子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值