LDAP 를 통 해 Active Directory 서비스 검증
18622 단어 Directory
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"][0];
}
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 = 0; propertyCounter < propertyCount; propertyCounter++)
{
dn = (string)result.Properties["memberOf"][propertyCounter];
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (-1 == equalsIndex)
{
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
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);
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Directory Entry 사용Directory Entry 예.넷이 우리에게 준 큰 선물, 그의 이름을 우리는 그의 기능인 목록 입구를 안다.ADSI를 사용한 사람들은 모두 IIS, WinNT 등을 조작할 때 우리는 그들의 Path를 제공해야 한...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.