通过LDAP验证Active Directory服务
原文地址: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服务的更多相关文章
- SRV记录用来标识某台服务器使用了某个服务,常见于微软系统的目录管理——深入的话需要去折腾Azure Active Directory
SRV记录 SRV记录 什么情况下会用到SRV记录? [SRV记录用来标识某台服务器使用了某个服务,常见于微软系统的目录管理] SRV记录的添加方式 A.主机记录处格式为:服务的名字.协议的类型 例如 ...
- Solaris与Windows Active Directory集成
通过Solaris与Active Directory的集成,Solaris可以使用Windows 2003 R2/ 2008 Active Directory来进行用户登录验证.以下是简要配置过程. ...
- install Active Directory域控制器
设置Active Directory域控制器 正如我们在网络与系统配置专题文章中所提到的那样,我们已将两部服务器设置为对应于内部域“intdomain.com”的Active Directory域控制 ...
- 用JAVA 查询 Active Directory(AD)
Required Details LDAP address (For e.g.: myjeeva.com or IP of the Domain Controller/Global Catalog[G ...
- Active Directory域
引言 在 Microsoft® Windows® 2000 Server 操作系统的诸多增强功能中,Microsoft Active Directory™ 功能的引入意义最为重大,但也最常引起困惑.与 ...
- Active Directory的LDAP协议与DN(Distinguished Name)详解
前言 光copy几段代码的文章没什么意思,本章上最基础的代码,主要是为了从编程方面聊LDAP和DN,其它的后面聊,一步步慢慢来吧. Active Directory编程须知 1.域控服务器: Wind ...
- 管理员技术(五): 配置文档的访问权限、 配置附加权限、绑定到LDAP验证服务、配置LDAP家目录漫游
一.配置文档的访问权限 问题: 本例要求将文件 /etc/fstab 拷贝为 /var/tmp/fstab,并调整文件 /var/tmp/fstab的权限,满足以下要求: 1> 此文件的拥有者 ...
- 移动服务和 Azure Active Directory 中基于角色的访问控制
编辑人员注释:本文章由 Matthew Henderson撰写 去年 11月,我们发布了 Azure Active Directory (AAD) 预览版作为移动服务身份提供程序.此举旨在为企业开 ...
- 如何通过使用窗体身份验证和 Visual C#.NET 对 Active Directory 验证身份
本分步指南演示如何在 ASP.NET 应用程序如何使用窗体身份验证允许用户使用轻型目录访问协议 (LDAP),对 Active Directory 进行验证.经过身份验证的用户重定向之后,可以使用Ap ...
随机推荐
- hdu 1533 KM或费用流
以前用KM写过,现在再用费用流写. #include <iostream> #include <cstdio> #include <cstring> #includ ...
- iOS防止button重复点击
项目中常会遇到在按钮的点击事件中去执行一些耗时操作.如果处理不当经常会出现连续多次点击push多次的情况,造成不好的用户体验. 一种情况是用户快速连续点击,这种情况无法避免.另一种情况是点击一次后响应 ...
- Python模块之: configobj(转)
原来也有写过一篇文章Python模块之: ConfigParser 用来解析INI文件,但是在使用过程中存在一些问题.比如:1,不能区分大小写.2,重新写入的ini文件不能保留原有INI文件的注释.3 ...
- 介绍:一款Mathematica的替代开源软件Mathetics
Mathetics软件 1 以Python语言实现该系统 2 软件使用的语法与Mathematica同样 3 下载:http://www.mathics.org/ 4 手冊:http://www.ma ...
- mysql求交集:UNION ALL合并查询,inner join内连接查询,IN/EXISTS子查询
两个要求交集的表(列)的结构要一致,对应的字段数,字段类型都应该相同:将两个数据的数据列用 UNION ALL 关键字合并:将上面的所有需要比较的列 GROUP BY :最后 HAVING COUNT ...
- Python学习(六)模块
Python 模块 模块定义 随着程序越来越庞大,需要分隔成几个文件:也需要能在不同文件中复用函数.类和变量,而不是拷贝代码.为了满足这些需要,Python提供了模块. 简单来说,模块就是一个保存了P ...
- ZeroMQZeroMQ研究与应用分析
1 ZeroMQ概述 ZeroMQ是一种基于消息队列的多线程网络库,其对套接字类型.连接处理.帧.甚至路由的底层细节进行抽象,提供跨越多种传输协议的套接字.ZeroMQ是网络通信中新的一层,介于应用 ...
- TestNG测试带参构造函数的类
今天被同事问到一个问题,问题描述如下: 一个测试类,只有一个带参构造函数.在带参构造函数上加@Test,同时加@Parameters注解从testng.xml中传递参数.为保证测试函数在带参构造函数之 ...
- myBatis批量添加,修改和删除
摘自: http://blog.csdn.net/myjlvzlp/article/details/8434376 1.批量添加元素session.insert(String string,Objec ...
- MyEclipse 如何最佳设置
摘自: http://blog.csdn.net/lifuxiangcaohui/article/details/8513561 MyEclipse 如何最佳设置 作为企业级开发最流行的工具,用Mye ...