原文地址: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. js 运算符 || && 妙用

    首先出个题:如图: 假设对成长速度显示规定如下:  成长速度为5显示1个箭头:  成长速度为10显示2个箭头:  成长速度为12显示3个箭头:  成长速度为15显示4个箭头:  其他都显示都显示0个箭 ...

  2. [转]Android Activity和Fragment的转场动画

    Android Activity和Fragment的转场动画 Activity转场动画 Activity的转场动画是通过overridePendingTransition(int enterAnim, ...

  3. 2015 百度之星 1004 KPI STL的妙用

    KPI Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://acdream.info/problem?pid=1754 Description 你 ...

  4. Cwrsync_rsync windows_windows下的rsync

    1.官网已不允许免费下载cwrsync的server了,我就先给出下载地址: http://files.cnblogs.com/files/assassin1994/cwRsync_4.0.5_ser ...

  5. ExtJs xtype一览

    标签: extjs xtype 分类: HTML 基本组件: xtype Class 描述 button Ext.Button 按钮 splitbutton Ext.SplitButton 带下拉菜单 ...

  6. javascript(js)自动刷新页面的实现方法总结

    自动刷新页面的实现方法总结: 1) <meta http-equiv="refresh"content="10;url=跳转的页面"> 10表示间隔 ...

  7. Ubuntu下gcc多版本共存和版本切换

    https://my.oschina.net/u/2306127/blog/538139 摘要: Ubuntu系统使用的gcc版本随着发布版本的不同而不同,在编译android系统时不同的版本推荐用不 ...

  8. Sublime的中文GBK显示乱码的解决方法

    import urllib2,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd ...

  9. linux集成开发环境

    Linux操作系统的种种集成开发环境 随着Linux的逐渐兴起,已经有为数众多的程序在上面驰骋了,许多开发环境(Development Environment)也应运而生.好的开发环境一定是集成了编辑 ...

  10. CocoaAsyncSocket 套接字

    CocoaAsyncSocket   套接字 https://github.com/robbiehanson/CocoaAsyncSocket Asynchronous socket networki ...