::
::
::
::
::
- using System;
- using System.DirectoryServices;
-
- namespace SystemFrameworks.Helper
- {
-
-
-
- public sealed class ADHelper
- {
-
-
-
- private static string DomainName = "MyDomain";
-
-
-
- private static string LDAPDomain = "DC=MyDomain,DC=local";
-
-
-
- private static string ADPath = "LDAP://brooks.mydomain.local";
-
-
-
- private static string ADUser = "Administrator";
-
-
-
- private static string ADPassword = "password";
-
-
-
- private static IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
-
-
-
-
- public enum LoginResult
- {
-
-
-
- LOGIN_USER_OK = 0,
-
-
-
- LOGIN_USER_DOESNT_EXIST,
-
-
-
- LOGIN_USER_ACCOUNT_INACTIVE,
-
-
-
- LOGIN_USER_PASSWORD_INCORRECT
- }
-
-
-
-
- public enum ADS_USER_FLAG_ENUM
- {
-
-
-
- ADS_UF_SCRIPT = 0X0001,
-
-
-
- ADS_UF_ACCOUNTDISABLE = 0X0002,
-
-
-
- ADS_UF_HOMEDIR_REQUIRED = 0X0008,
-
-
-
- ADS_UF_LOCKOUT = 0X0010,
-
-
-
- ADS_UF_PASSWD_NOTREQD = 0X0020,
-
-
-
- ADS_UF_PASSWD_CANT_CHANGE = 0X0040,
-
-
-
- ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,
-
-
-
- ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100,
-
-
-
- ADS_UF_NORMAL_ACCOUNT = 0X0200,
-
-
-
- ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800,
-
-
-
- ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,
-
-
-
- ADS_UF_SERVER_TRUST_ACCOUNT = 0X2000,
-
-
-
- ADS_UF_DONT_EXPIRE_PASSWD = 0X10000,
-
-
-
- ADS_UF_MNS_LOGON_ACCOUNT = 0X20000,
-
-
-
- ADS_UF_SMARTCARD_REQUIRED = 0X40000,
-
-
-
- ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000,
-
-
-
- ADS_UF_NOT_DELEGATED = 0X100000,
-
-
-
- ADS_UF_USE_DES_KEY_ONLY = 0X200000,
-
-
-
- ADS_UF_DONT_REQUIRE_PREAUTH = 0X4000000,
-
-
-
- ADS_UF_PASSWORD_EXPIRED = 0X800000,
-
-
-
- ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000
- }
-
- public ADHelper()
- {
-
- }
-
- #region GetDirectoryObject
-
-
-
-
-
- private static DirectoryEntry GetDirectoryObject()
- {
- DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
- return entry;
- }
-
-
-
-
-
-
-
- private static DirectoryEntry GetDirectoryObject(string userName, string password)
- {
- DirectoryEntry entry = new DirectoryEntry(ADPath, userName, password, AuthenticationTypes.None);
- return entry;
- }
-
-
-
-
-
-
- private static DirectoryEntry GetDirectoryObject(string domainReference)
- {
- DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, ADUser, ADPassword, AuthenticationTypes.Secure);
- return entry;
- }
-
-
-
-
-
-
-
-
- private static DirectoryEntry GetDirectoryObject(string domainReference, string userName, string password)
- {
- DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, userName, password, AuthenticationTypes.Secure);
- return entry;
- }
-
- #endregion
-
- #region GetDirectoryEntry
-
-
-
-
-
-
- public static DirectoryEntry GetDirectoryEntry(string commonName)
- {
- DirectoryEntry de = GetDirectoryObject();
- DirectorySearcher deSearch = new DirectorySearcher(de);
- deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
- deSearch.SearchScope = SearchScope.Subtree;
-
- try
- {
- SearchResult result = deSearch.FindOne();
- de = new DirectoryEntry(result.Path);
- return de;
- }
- catch
- {
- return null;
- }
- }
-
-
-
-
-
-
-
- public static DirectoryEntry GetDirectoryEntry(string commonName, string password)
- {
- DirectoryEntry de = GetDirectoryObject(commonName, password);
- DirectorySearcher deSearch = new DirectorySearcher(de);
- deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
- deSearch.SearchScope = SearchScope.Subtree;
-
- try
- {
- SearchResult result = deSearch.FindOne();
- de = new DirectoryEntry(result.Path);
- return de;
- }
- catch
- {
- return null;
- }
- }
-
-
-
-
-
-
- public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName)
- {
- DirectoryEntry de = GetDirectoryObject();
- DirectorySearcher deSearch = new DirectorySearcher(de);
- deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))";
- deSearch.SearchScope = SearchScope.Subtree;
-
- try
- {
- SearchResult result = deSearch.FindOne();
- de = new DirectoryEntry(result.Path);
- return de;
- }
- catch
- {
- return null;
- }
- }
-
-
-
-
-
-
-
- public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName, string password)
- {
- DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
- if (de != null)
- {
- string commonName = de.Properties["cn"][0].ToString();
-
- if (GetDirectoryEntry(commonName, password) != null)
- return GetDirectoryEntry(commonName, password);
- else
- return null;
- }
- else
- {
- return null;
- }
- }
-
-
-
-
-
-
- public static DirectoryEntry GetDirectoryEntryOfGroup(string groupName)
- {
- DirectoryEntry de = GetDirectoryObject();
- DirectorySearcher deSearch = new DirectorySearcher(de);
- deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";
- deSearch.SearchScope = SearchScope.Subtree;
-
- try
- {
- SearchResult result = deSearch.FindOne();
- de = new DirectoryEntry(result.Path);
- return de;
- }
- catch
- {
- return null;
- }
- }
-
- #endregion
-
- #region GetProperty
-
-
-
-
-
-
-
- public static string GetProperty(DirectoryEntry de, string propertyName)
- {
- if(de.Properties.Contains(propertyName))
- {
- return de.Properties[propertyName][0].ToString() ;
- }
- else
- {
- return string.Empty;
- }
- }
-
-
-
-
-
-
-
- public static string GetProperty(SearchResult searchResult, string propertyName)
- {
- if(searchResult.Properties.Contains(propertyName))
- {
- return searchResult.Properties[propertyName][0].ToString() ;
- }
- else
- {
- return string.Empty;
- }
- }
-
- #endregion
-
-
-
-
-
-
-
- public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)
- {
- if(propertyValue != string.Empty || propertyValue != "" || propertyValue != null)
- {
- if(de.Properties.Contains(propertyName))
- {
- de.Properties[propertyName][0] = propertyValue;
- }
- else
- {
- de.Properties[propertyName].Add(propertyValue);
- }
- }
- }
-
-
-
-
-
-
-
-
-
- public static DirectoryEntry CreateNewUser(string ldapDN, string commonName, string sAMAccountName, string password)
- {
- DirectoryEntry entry = GetDirectoryObject();
- DirectoryEntry subEntry = entry.Children.Find(ldapDN);
- DirectoryEntry deUser = subEntry.Children.Add("CN=" + commonName, "user");
- deUser.Properties["sAMAccountName"].Value = sAMAccountName;
- deUser.CommitChanges();
- ADHelper.EnableUser(commonName);
- ADHelper.SetPassword(commonName, password);
- deUser.Close();
- return deUser;
- }
-
-
-
-
-
-
-
-
- public static DirectoryEntry CreateNewUser(string commonName, string sAMAccountName, string password)
- {
- return CreateNewUser("CN=Users", commonName, sAMAccountName, password);
- }
-
-
-
-
-
-
- public static bool IsUserExists(string commonName)
- {
- DirectoryEntry de = GetDirectoryObject();
- DirectorySearcher deSearch = new DirectorySearcher(de);
- deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
- SearchResultCollection results = deSearch.FindAll();
-
- if (results.Count == 0)
- return false;
- else
- return true;
- }
-
-
-
-
-
-
- public static bool IsAccountActive(int userAccountControl)
- {
- int userAccountControl_Disabled = Convert.ToInt32(ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE);
- int flagExists = userAccountControl & userAccountControl_Disabled;
-
- if (flagExists > 0)
- return false;
- else
- return true;
- }
-
-
-
-
-
-
-
- public static LoginResult Login(string commonName, string password)
- {
- DirectoryEntry de = GetDirectoryEntry(commonName);
-
- if (de != null)
- {
-
- int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);
- de.Close();
-
- if (!IsAccountActive(userAccountControl))
- return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
-
- if (GetDirectoryEntry(commonName, password) != null)
- return LoginResult.LOGIN_USER_OK;
- else
- return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
- }
- else
- {
- return LoginResult.LOGIN_USER_DOESNT_EXIST;
- }
- }
-
-
-
-
-
-
-
- public static LoginResult LoginByAccount(string sAMAccountName, string password)
- {
- DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
-
- if (de != null)
- {
-
- int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);
- de.Close();
-
- if (!IsAccountActive(userAccountControl))
- return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
-
- if (GetDirectoryEntryByAccount(sAMAccountName, password) != null)
- return LoginResult.LOGIN_USER_OK;
- else
- return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
- }
- else
- {
- return LoginResult.LOGIN_USER_DOESNT_EXIST;
- }
- }
-
-
-
-
-
-
- public static void SetPassword(string commonName, string newPassword)
- {
- DirectoryEntry de = GetDirectoryEntry(commonName);
-
-
- impersonate.BeginImpersonate();
- de.Invoke("SetPassword", new object[]{newPassword});
- impersonate.StopImpersonate();
-
- de.Close();
- }
-
-
-
-
-
-
- public static void SetPasswordByAccount(string sAMAccountName, string newPassword)
- {
- DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
-
-
- IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
- impersonate.BeginImpersonate();
- de.Invoke("SetPassword", new object[]{newPassword});
- impersonate.StopImpersonate();
-
- de.Close();
- }
-
-
-
-
-
-
-
- public static void ChangeUserPassword (string commonName, string oldPassword, string newPassword)
- {
-
- DirectoryEntry oUser = GetDirectoryEntry(commonName);
- oUser.Invoke("ChangePassword", new Object[]{oldPassword, newPassword});
- oUser.Close();
- }
-
-
-
-
-
- public static void EnableUser(string commonName)
- {
- EnableUser(GetDirectoryEntry(commonName));
- }
-
-
-
-
-
- public static void EnableUser(DirectoryEntry de)
- {
- impersonate.BeginImpersonate();
- de.Properties["userAccountControl"][0] = ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;
- de.CommitChanges();
- impersonate.StopImpersonate();
- de.Close();
- }
-
-
-
-
-
- public static void DisableUser(string commonName)
- {
- DisableUser(GetDirectoryEntry(commonName));
- }
-
-
-
-
-
- public static void DisableUser(DirectoryEntry de)
- {
- impersonate.BeginImpersonate();
- de.Properties["userAccountControl"][0]=ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE;
- de.CommitChanges();
- impersonate.StopImpersonate();
- de.Close();
- }
-
-
-
-
-
-
- public static void AddUserToGroup(string userCommonName, string groupName)
- {
- DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
- DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
-
- impersonate.BeginImpersonate();
- oGroup.Properties["member"].Add(oUser.Properties["distinguishedName"].Value);
- oGroup.CommitChanges();
- impersonate.StopImpersonate();
-
- oGroup.Close();
- oUser.Close();
- }
-
-
-
-
-
-
- public static void RemoveUserFromGroup(string userCommonName, string groupName)
- {
- DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
- DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
-
- impersonate.BeginImpersonate();
- oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value);
- oGroup.CommitChanges();
- impersonate.StopImpersonate();
-
- oGroup.Close();
- oUser.Close();
- }
-
- }
-
-
-
-
- public class IdentityImpersonation
- {
- [DllImport("advapi32.dll", SetLastError=true)]
- public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
-
- [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
- public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
-
- [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
- public extern static bool CloseHandle(IntPtr handle);
-
-
- private String _sImperUsername;
- private String _sImperPassword;
- private String _sImperDomain;
-
- private WindowsImpersonationContext _imperContext;
- private IntPtr _adminToken;
- private IntPtr _dupeToken;
-
- private Boolean _bClosed;
-
-
-
-
-
-
-
- public IdentityImpersonation(String impersonationUsername, String impersonationPassword, String impersonationDomain)
- {
- _sImperUsername = impersonationUsername;
- _sImperPassword = impersonationPassword;
- _sImperDomain = impersonationDomain;
-
- _adminToken = IntPtr.Zero;
- _dupeToken = IntPtr.Zero;
- _bClosed = true;
- }
-
-
-
-
- ~IdentityImpersonation()
- {
- if(!_bClosed)
- {
- StopImpersonate();
- }
- }
-
-
-
-
-
- public Boolean BeginImpersonate()
- {
- Boolean bLogined = LogonUser(_sImperUsername, _sImperDomain, _sImperPassword, 2, 0, ref _adminToken);
-
- if(!bLogined)
- {
- return false;
- }
-
- Boolean bDuped = DuplicateToken(_adminToken, 2, ref _dupeToken);
-
- if(!bDuped)
- {
- return false;
- }
-
- WindowsIdentity fakeId = new WindowsIdentity(_dupeToken);
- _imperContext = fakeId.Impersonate();
-
- _bClosed = false;
-
- return true;
- }
-
-
-
-
- public void StopImpersonate()
- {
- _imperContext.Undo();
- CloseHandle(_dupeToken);
- CloseHandle(_adminToken);
- _bClosed = true;
- }
- }
- }
-
- 简单的应用
- [WebMethod]
- public string IsAuthenticated(string UserID,string Password)
- {
- string _path = "LDAP://" + adm + "/DC=lamda,DC=com,DC=cn";//"LDAP://172.75.200.1/DC=名字,DC=com,DC=cn";
- string _filterAttribute=null;
-
- DirectoryEntry entry = new DirectoryEntry(_path,UserID,Password);
-
- try
- {
-
- DirectorySearcher search = new DirectorySearcher(entry);
- search.Filter = "(SAMAccountName=" + UserID + ")";
- SearchResult result = search.FindOne();
-
- if(null == result)
- {
- _filterAttribute="登录失败: 未知的用户名或错误密码.";
- }
- else
- {
- _filterAttribute="true";
- }
-
- }
- catch (Exception ex)
- {
-
-
- return ex.Message;
- }
- return _filterAttribute;
- }
- [WebMethod]
- public string[] LDAPMessage(string UserID)
- {
- string _path = "LDAP://"+adm+"/DC=it2004,DC=名字,DC=com,DC=cn";
- string[] _filterAttribute=new string[5];
- string[] msg = {"samaccountname","displayname","department","company"};
- DirectoryEntry entry = new DirectoryEntry(_path,"180037","790813");
-
- try
- {
-
- Object obj = entry.NativeObject;
-
- DirectorySearcher search = new DirectorySearcher(entry);
- search.Filter = "(SAMAccountName=" + UserID + ")";
- SearchResult result = search.FindOne();
-
- if(null == result)
- {
- _filterAttribute[0]="登录失败: 未知的用户名或错误密码.";
- }
- else
- {
- _filterAttribute[0]="true";
- for(int propertyCounter = 1; propertyCounter < 5; propertyCounter++)
- {
-
- if(propertyCounter==4 && result.Properties[msg[propertyCounter-1]][0]==null)
- break;
- _filterAttribute[propertyCounter]=result.Properties[msg[propertyCounter-1]][0].ToString();
-
- }
- }
-
- }
- catch (Exception ex)
- {
-
- }
- return _filterAttribute;
- }
- [WebMethod]
- public string[] AllMembers()
- {
-
- string[] msg;
- string _path = "LDAP://名字";
- DirectoryEntry entry = new DirectoryEntry(_path,"180037","790813");
-
-
-
- Object obj = entry.NativeObject;
- System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);
- mySearcher.Filter = "(SAMAccountName=180037)";
- msg=new string[mySearcher.FindAll().Count];
- int i=0;
- foreach(System.DirectoryServices.SearchResult result in mySearcher.FindAll())
- {
- msg[i++]=result.Path;
- }
- return msg;
- }
-
- }
-
posted on
2012-10-09 09:00
王玉涛
阅读(
499)
评论()
收藏
举报