原文地址:http://www.byywee.com/page/M0/S215/215725.html

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.Configuration;
using System.Text.RegularExpressions; namespace ldapcs
{
class Program
{
static void Main(string[] args)
{
string path = "LDAP://192.168.137.210:389/ou=pet,dc=abc,dc=com ";
string username = "uname";
string pwd = "upwd";
string domain = "abc.com"; LdapAuthentication ldap = new LdapAuthentication(path);
Console.WriteLine( ldap.IsAuthenticated(domain, username, pwd));
Console.WriteLine(ldap.GetGroups());
} public class LdapAuthentication
{
private string _path;
private string _filterAttribute; public LdapAuthentication(string path)
{
_path = path;
} public bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, username, pwd); try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne(); if (null == result)
{
return false;
} //Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
} return true;
} public string GetGroups()
{
DirectorySearcher search = new DirectorySearcher(_path);
search.Filter = "(cn=" + _filterAttribute + ")";
//search.SearchRoot = "PET";
StringBuilder groupNames = new StringBuilder(); try
{
SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
string dn;
int equalsIndex, commaIndex; for (int propertyCounter = ; propertyCounter < propertyCount; propertyCounter++)
{
dn = (string)result.Properties["memberOf"][propertyCounter];
equalsIndex = dn.IndexOf("=", );
commaIndex = dn.IndexOf(",", );
if (- == equalsIndex)
{
return null;
}
groupNames.Append(dn.Substring((equalsIndex + ), (commaIndex - equalsIndex) - ));
groupNames.Append("|");
}
}
catch (Exception ex)
{
throw new Exception("Error obtaining group names. " + ex.Message);
}
return groupNames.ToString();
}
} /// <summary>
/// 验证AD用户是否登录成功
/// </summary>
/// <param name="domain"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public static bool TryAuthenticate(string domain, string userName, string password)
{
bool isLogin = false;
try
{
DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), userName, password);
entry.RefreshCache();
isLogin = true;
}
catch
{
isLogin = false;
}
return isLogin;
}
}
}

Java:

import java.util.Hashtable;
import java.util.Enumeration;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls ;
import javax.naming.NamingEnumeration;
import javax.naming.directory.SearchResult; public class LDAPtest { public static void main(String[] args) {
LDAPtest ldap=new LDAPtest();
ldap.init();
}
public void init(){
DirContext ctx = null;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://192.168.137.210:389/");//连接LDAP的URL和端口 //env.put(Context.SECURITY_AUTHENTICATION, "simple");//以simple方式发送
env.put(Context.SECURITY_PRINCIPAL, "cn=uname,ou=PET,DC=abc,DC=com");//用户名
env.put(Context.SECURITY_CREDENTIALS, "upwd");//密码
String baseDN="ou=PET,DC=abc,DC=com";//查询区域
String filter="(&(objectClass=person))";//条件查询 try{
ctx = new InitialDirContext(env);//连接LDAP服务器
System.out.println("Success");
SearchControls constraints = new SearchControls();//执行查询操作
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration en=ctx.search(baseDN, filter, constraints);
if(en==null){
System.out.println("There have no value");
}else{
while(en.hasMoreElements()){ Object obj=en.nextElement();
if(obj instanceof SearchResult){
SearchResult sr=(SearchResult) obj;
String cn=sr.getName(); System.out.println("cccccc: "+cn);
}
}
} }catch(javax.naming.AuthenticationException e){
System.out.println(e.getMessage());
}catch(Exception e){
System.out.println("erro:"+e);
}
}
}

通过LDAP验证Active Directory服务的更多相关文章

  1. SRV记录用来标识某台服务器使用了某个服务,常见于微软系统的目录管理——深入的话需要去折腾Azure Active Directory

    SRV记录 SRV记录 什么情况下会用到SRV记录? [SRV记录用来标识某台服务器使用了某个服务,常见于微软系统的目录管理] SRV记录的添加方式 A.主机记录处格式为:服务的名字.协议的类型 例如 ...

  2. Solaris与Windows Active Directory集成

    通过Solaris与Active Directory的集成,Solaris可以使用Windows 2003 R2/ 2008 Active Directory来进行用户登录验证.以下是简要配置过程. ...

  3. install Active Directory域控制器

    设置Active Directory域控制器 正如我们在网络与系统配置专题文章中所提到的那样,我们已将两部服务器设置为对应于内部域“intdomain.com”的Active Directory域控制 ...

  4. 用JAVA 查询 Active Directory(AD)

    Required Details LDAP address (For e.g.: myjeeva.com or IP of the Domain Controller/Global Catalog[G ...

  5. Active Directory域

    引言 在 Microsoft® Windows® 2000 Server 操作系统的诸多增强功能中,Microsoft Active Directory™ 功能的引入意义最为重大,但也最常引起困惑.与 ...

  6. Active Directory的LDAP协议与DN(Distinguished Name)详解

    前言 光copy几段代码的文章没什么意思,本章上最基础的代码,主要是为了从编程方面聊LDAP和DN,其它的后面聊,一步步慢慢来吧. Active Directory编程须知 1.域控服务器: Wind ...

  7. 管理员技术(五): 配置文档的访问权限、 配置附加权限、绑定到LDAP验证服务、配置LDAP家目录漫游

    一.配置文档的访问权限 问题: 本例要求将文件 /etc/fstab 拷贝为 /var/tmp/fstab,并调整文件 /var/tmp/fstab的权限,满足以下要求: 1>  此文件的拥有者 ...

  8. 移动服务和 Azure Active Directory 中基于角色的访问控制

    编辑人员注释:本文章由 Matthew Henderson撰写 去年 11月,我们发布了 Azure Active Directory (AAD) 预览版作为移动服务身份提供程序.此举旨在为企业开 ...

  9. 如何通过使用窗体身份验证和 Visual C#.NET 对 Active Directory 验证身份

    本分步指南演示如何在 ASP.NET 应用程序如何使用窗体身份验证允许用户使用轻型目录访问协议 (LDAP),对 Active Directory 进行验证.经过身份验证的用户重定向之后,可以使用Ap ...

随机推荐

  1. JSP myecplise项目移植到ecplise

    把myecplise项目移植到ecplise的一些细节: 参考于http://www.cnblogs.com/liushuijinger/p/3396063.html 因为个人需要,需要把JSP项目从 ...

  2. 更新yum源/apt-get源

    国内开源镜像站有:网易: http://mirrors.163.com/ 搜狐: http://mirrors.sohu.com/阿里云: http://mirrors.aliyun.com/北京理工 ...

  3. 【java失业择业中】失业第四天:准备面试

    1.jQuery基础 学好jquery的一个基础条件是学好css层叠样式,因为很多时候这2个是一块配合使用的. 页面中很多需要jquery实现的效果只是通过jquery的选择器,选中要操作的元素,添加 ...

  4. 【mybatis】mybatis访问报错:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) 或者 feign被调用方使用的mybatis总报空指针异常java.lang.NullPointerException,而变量都没有问题的情况

    mybatis访问报错:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) 需要检查的步骤: ...

  5. ODS与数据仓库

    数据仓库是目前主要的数据存储体系.数据仓库之增W.H.Inmon认为,数据仓库是指支持管理决策过程的.面向主题的.集成的.随时间而变的.持久的数据的集合.简单地说,一个数据仓库就一个自数据库的商业应用 ...

  6. Nginx集群

    转自:http://hi.baidu.com/xingyuanju/blog/item/779a2a23b7ebb749935807f1.html http://hi.baidu.com/dianhu ...

  7. 第一章 在linux下python读串口 存MYSQL数据库(703N)

    import MySQLdb//定义引用数据库的驱动文件 import serial import time ser = serial.Serial('/dev/ttyATH0', 115200, t ...

  8. zendstudio采用xdebug调试,断点不停的解决

    查看zendstudio里windows->preferences->PHP->PHP Executables,编辑列表项,弹出框的Debugger看看还是不是xdebug.

  9. Easyui NumberBox格式化展示

    格式化效果: 源代码: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> & ...

  10. CSS学习要点

    目标 掌握CSS基本语法,了解如何应用CSS到Html元素上并能熟练使用CSS进行元素布局. 要点 CSS基本概念.存在的意义 CSS 指层叠样式表 (Cascading Style Sheets), ...