通过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 ...
随机推荐
- bzoj 2038 小Z的袜子 莫队算法
题意 给你一个长度序列,有多组询问,每次询问(l,r)任选两个数相同的概率.n <= 50000,数小于等于n. 莫队算法裸题. 莫队算法:将序列分为根号n段,将询问排序,以L所在的块为第一关键 ...
- HDU 5641 King's Phone 模拟
King's Phone 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5641 Description In a military parade, ...
- Object-C—集合
Obejct-C中包含了三种集合,分别是:数组.字典和集(set). 数组和C语言中的数组相似,但是OC中的数组只能存储对象,不能存储基本数据类型,如int.float.enum.stru ...
- 【JS】 JS毫秒值转化为正常格式 或者正常格式转化为毫秒值
1.毫秒值转化为正常时间格式 最简单的方法 new Date(后台传来的毫秒值).toLocaleDateString() 就是这个样子 2.毫秒值转化为自定义的时间格式 本页面重写一下 toLo ...
- UIScrollView 几乎所有的属性和方法
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typica ...
- 负载均衡---在window与linux下配置nginx
最近有些时间,开始接触负载均衡方面的东西,从硬件F5再到Citrix Netscalar.不过因为硬件的配置虽然不复杂,但昂贵的价格也让一般用户望而却步(十几万到几十万),所以只能转向nginx,sq ...
- Visual Studio 2012连接TFS2010登录不了
一直用VS2012+TFS2010开发项目, 最近几天忽然很不正常, 在VS中会频繁要求输入TFS的账号密码, 经常要输入很多遍才可以正常连接签入签出. 这几天更甚, 基本上直接连接不了了. 网上找到 ...
- [Android Studio] Android Studio使用教程(一)
转载:http://blog.csdn.net/hyr83960944/article/details/37509113 今年的Google全球开发者 大会虽然没有新的Android系统和设备,但是还 ...
- SRM 212 Div II Level Two: WinningRecord,Brute Force
题目来源:http://community.topcoder.com/stat?c=problem_statement&pm=3003&rd=5858 比较简单. 代码如下: #inc ...
- calibre,完成对各种格式的电子书籍的管理和格式转换及同步
Calibre是免费的电子书制作.阅读软件,源代码开放,拥有跨平台的设计,支持多个基于不同系统的便携式移动设备,包括苹果iPhone.Amazon电子书等设备.它是一个完整的电子图书馆,包括图书馆管理 ...