原文地址: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. php上传文件常见问题(基础)

    既然上一篇文章<php上传中文文件文件名乱码问题>遇到了文件上传的问题,干脆把php上传文件时经常碰到的几个问题总结一下吧,以后用到时不用再去找了. 1.先做个最简单的上传文件 <h ...

  2. JQ 数组动态添值,对象动态添值,判断数组/对象是否为空

    1.数组动态添值 首先声明一个空数组:var data = new Array(); 向数组中添值 :data.push('添加的值'); 示例:

  3. Java容器-引入Guava类库

    目录 1.只读设置 2.函数式编程+组合式编程 3.约束条件 4.集合操作(并集.差集.交集) 代码实现 1.只读设置 public static void main(String [] args){ ...

  4. Linux下查找命令(收集整理)

    原文:http://blog.csdn.net/sunstars2009918/article/details/8510878 一.Linux查找文件的相关命令 常 用 命 令 简要中文说明 程序所在 ...

  5. iOS开源项目:PullToRefresh

    PullToRefresh实现了类似微博下拉刷新的功能:https://github.com/sonnyparlin/PullToRefresh 首先把PullToRefreshView.h, Pul ...

  6. UltraISO制作ISO镜像文件

    怎样制作一个ISO的镜像文件呢,镜像文件的应用范围比较广泛,最常见的应用就是数据备份(如软盘和光盘).随着宽带网的普及,有些下载网站也有了ISO格式的文件下载,方便了软件光盘的制作与传递.常见的镜像文 ...

  7. Redis安装、主从配置及aof使用

    找了02,03,04三台机器,04做主,02做从,03做客户端. 都使用jumbo install redis安装了Redis(server+client). 在 02 从的 ~/.jumbo/etc ...

  8. Centos7 安装pycharm

    可以通过浏览器访问http://www.jetbrains.com/pycharm/,选择需要下载的版本,也可以通过wget下载可执行程序. [root@localhost ~] wget https ...

  9. hdu 1158-Employment Planning,n*n*n

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1158 解题思路就不多说,动态规划. 值得提及的是题目没有给出数据范围,水过的都默认工人数目不超过100 ...

  10. 【转】Android:最全面的 Webview 详解

    原文: https://blog.csdn.net/carson_ho/article/details/52693322 前言 现在很多App里都内置了Web网页(Hyprid App),比如说很多电 ...