Adhelper Active Directory User Operation Class
*********************************************************** *********************************************************** ************
Using system; using system.directoryservices; namespace systemframeworks.helper {/// //A Active Directory Auxiliary class. Package a series of active directory operations related methods. /// Public Sealed Class Adhelper {///// Domain Name // Private Static String DomainName = "Mydomain"; /// /// LDAP Address /// Private Static String LdapDomain = "DC =
Mydomain
,
DC
= local "; /// /// LDAP binding path /// private static string adpath =" ldap://brooks.mydomain.local "; // /// Login account ///////////pring static string aduser = "Administrator"; /// /// password /// private static string ADPassword = "password"; /// /// playing instance /// private static IdentityImpersonation impersonate = new IdentityImpersonation (ADUser, ADPassword, DomainName) ; ///// User login verification result /// public enum loginResult {///// Normal login /// Login_user_ok = 0, /// // User does not exist /// Login_user_doesNT_EXIST, /// /// User account is disabled /// login_user_account_inactive, // /// user password is not correct /// login_user_password_incorRect} /// /// User Properties Definition Sign / // Public Enum ADS_USER_FLAG_ENUM {/// /// The login script flag. This flag is invalid if you read or write through the ADSI LDAP. If you pass through the ADSI WINNT, the logo is read-only.
/// ads_uf_script = 0x0001, // /// User account disabled flag /// ads_uf_accountdisable = 0x0002, ///// Main folder flag //////////////////////////////////////////////// /// /// // 过 期 标 / / 00 // ADS_UF_LOCKOUT = 0x0010, /// /// User Password is not a must /// ADS_UF_PASSWD_NOTREQD = 0x0020, /// /// password cannot be changed to change the flag /// ADS_UF_PASSWD_CANT_CHANGE = 0x0040, // / /// Use reversible and encrypted passwords /// ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080, /// /// local account sign /// ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100, /// /// ordinary user's default account type /// ADS_UF_NORMAL_ACCOUNT = 0X0200, /// // / Cross-domain trust account logo /// ads _UF_INTERDOMAIN_TRUST_ACCOUNT = 0x0800, /// // Workstation Trust account sign /// ads_uf_WorkStation_Trust_Account = 0x1000, ///// server trust account logo /// ADS_UF_SERVER_TRUST_ACCOUNT = 0x2000, /// /// password never expired flag / // ADS_UF_DONT_EXPIRE_PASSWD = 0x10000, // /// MNS account logo /// ADS_UF_MNS_LOGON_ACCOUNT = 0x20000, // / // // ////////////////////////////// When set Service account (
User or computer account will be trusted with Kerberos /// ADS_UF_TRUSTED_FOR_DELEGATION = 0x80000, // / / When the flag is set, even if the service account is trusted by Kerberos, the sensitive account cannot be delegated /// ADS_UF_NOT_DELEGATED = 0x100000 , // // This account requires DES encryption type /// ADS_UF_USE_DES_KEY_ONLY = 0x200000, // / / / Do not perform Kerberos Pre-authentication /// ADS_UF_DONT_REQUIRE_PREAUTH = 0x4000000, /// // User Password Expiral Sign / // ADS_UF_PASSWORD_EXPIRED = 0X800000, /// /// can delegate user account flag /// ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000} public ADHelper () {//} #region GetDirectoryObject /// /// obtained DirectoryEntry object instance, an administrator login Ad // /// Private Static DirectoryEntry GetDirectoryObject () {Directo Ryentry 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;} /// /// ie / CN = Users, DC = creditsights, DC = Cyberelves, DC = COM / / / / / / / /
private static DirectoryEntry GetDirectoryObject (string domainReference) {DirectoryEntry entry = new DirectoryEntry (ADPath domainReference, ADUser, ADPassword, AuthenticationTypes.Secure); return entry;} /// /// DirectoryEntry to obtain UserName, Password created /// / // /// /// /// 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 / / / / / / / According to user public names
Object / / / / User Public Name ///
If you find the user, return to the user.
Objects; otherwise null 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; }} // / / / Nake the user according to user public name and password
Object. /// // User Public Name /// User Password ///
If you find the user, return to the user.
Objects; otherwise 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;}} // / / / / / / / / / / / / /
If you find the user, return to the user.
Objects; otherwise 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; }} // / / / Once the user is obtained according to user account and password
Object // / // User Account Name /// User Password // If you find the user, return to the user
Objects; otherwise 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;}}} // // / User Group
Object // /// Group name ///
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 /// /// Get designated
Specifies the value corresponding to the attribute name /////
/// Attribute Name ///
Attribute value public static string GetProperty (DirectoryEntry de, string propertyName) {if (de.Properties.Contains (propertyName)) {return de.Properties [propertyName] [0] .ToString ();} else {return string.Empty;} } // /// Get the value corresponding to the specified property name in the specified search result ////
/// Attribute Name ///
Attribute value public static string GetProperty (SearchResult searchResult, string propertyName) {if (searchResult.Properties.Contains (propertyName)) {return searchResult.Properties [propertyName] [0] .ToString ();} else {return string.Empty;} } #ENDREGION / / / / / / set specified
Attribute value / / / / /
/// /// attribute name attribute value public static void SetProperty (DirectoryEntry de, string propertyName, string propertyValue) {if (propertyValue! = String.Empty || propertyValue! = "" || propertyValue! = Null) {if ( de.properties.contains) {de.properties [PropertyName] [0] = PropertyValue;} else {de.properties [PropertyName] .add (propertyValue);}}} /// // Create a new user /// // DN position. For example: OU = shared platform or cn = users // / public name /// account /// password ///
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;} // / / / Create a new user. Create by default under the Users unit. /// /// /// common name account password /// /// public static DirectoryEntry CreateNewUser (string commonName, string sAMAccountName, string password) {return CreateNewUser ( "CN = Users", commonName, sAMAccountName, password); } /// // Determine if the user of the specified public name exists / / // User public name ///
If present, returns true; otherwise returns false public static bool IsUserExists (string commonName) {DirectoryEntry de = GetDirectoryObject (); DirectorySearcher deSearch = new DirectorySearcher (de); deSearch.Filter = "(& (& (objectCategory = person) (objectClass = User)) (CN = " CommonName ") ")"; // LDAP query string searchResultCollection results = desearch.Findall (); if (results.count == 0) Return False; else return true;} //// /// Determine if the user account is activated /// // User account attribute controller /// If the user account is activated, return true; otherwise return false public static bool isaccountactive (int useractControl) {int useercountControl_disabled = Convert.Toint32 ( ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE); int flagXists = UseraccountControl & UseraccountControl_disabled; if (FLAGEXISTS> 0) Return False; Else Return True;} // /// Determine if the user and the password are sufficient to meet the authentication and then log in /// // User public name /// password ///
If you can log in normally, return true; otherwise return false public static loginResult login (string commonname, string password) {DirectoryEntry de = getDirectoryEntry (Commonname); if (de! = Null) {// must be correct before judging the user password , Judge the account activation attribute; otherwise an exception will occur. 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;}} /// /// determines whether the user account and password to authenticate enough to satisfy the user account further logged /// /// / // password ///
As can be normal login, it returns true; otherwise false public static LoginResult LoginByAccount (string sAMAccountName, string password) {DirectoryEntry de = GetDirectoryEntryByAccount (sAMAccountName); if (! De = null) {// must be judged before the user password is correct , Judge the account activation attribute; otherwise an exception will occur. 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 returnger_USE RETURN LoginResult.login_user_parsword_incorRect;} else {return loginResult;}} /// /// Set user password, the administrator can modify the specified user's password. /// // User Public Name /// User New Password Public Static Void SetPassword (String Commonname, String NewPassword) {DirectoryEntry DE = getDirectoryEntry (Commonname); // Simulate Super Administrator to achieve permission to modify user password Impersonate .Beginimpersonate (); de.invoke ("setpassword", new object [] {newpassword}; impersonate.stopimpersonate (); de.close ();} /// // / set account password, administrator can pass it To modify the password of the specified account.
/// /// /// user account password new user public static void SetPasswordByAccount (string sAMAccountName, string newPassword) {DirectoryEntry de = GetDirectoryEntryByAccount (sAMAccountName); // simulation super administrator to achieve have permission to modify user password IdentityImpersonation impersonate = new IdentityImpersonation (ADUser, ADPassword, DomainName); impersonate.BeginImpersonate (); de.Invoke ( "SetPassword", new object [] {newPassword}); impersonate.StopImpersonate (); de.Close ();} /// /// Modify User Password /// // User Public Name /// Old Password /// New Password Public Static Void ChangeUserpassword (String Commonname, String Oldpassword, String NewPassword) {// TO-DO: Need to Resolve Password Policy Problem DirectoryEntry Ouser = getdirectoryEntry; OUSER.INVOKE ("ChangePassword", new object [] {oldpassword, newpassword}); OUSER.CLOSE ();} // // Enable the user //// user public name public static void enableuser (GetDirectoryEntry);} // // /// /// /// /// /////> Enable the specified user / ////
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 ();} // // Disable User //// User Public Name Public Static Void Disableuser (String CommonName);} /// /// Disable the specified user ////
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 ();} // // Add the specified user to the specified group. The group and user under Users. /// /// /// common name of the user group name 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 ();} /// / // Remove the user from the specified group. The group and user under Users.
/// /// /// common name of the user group name 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 ();}} /// /// User simulates the role class. Implement the user role simulation within the block.
/// 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); // to simulate the user's user name, password, domain (machine name) private String _sImperUsername; private String _sImperPassword; private String _sImperDomain; // record simulation context private WindowsImpersonationContext _imperContext; private IntPtr _admintoken; private intptr _duPToken; // Have you stopped simulation private boolean _bclosed; // /// constructor /// /// to be simulated user name of the user to be simulated /// user password /// public domain users to be simulated where IdentityImpersonation (String impersonationUsername, String impersonationPassword, String impersonationDomain) {_sImperUsername = impersonationUsername; _sImperPassword = impersonationPassword; _sImperDomain = impersonationDomain; _adminToken = IntPtr.Zero; _dupeToken = IntPtr.Zero; _bClosed = true;} /// /// destructor /// ~ IdentityImpersonation () {if (! _ bClosed) {StopImpersonate () ;
}} // /// Start identity role simulation. /// /// 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;} /// /// stop identity role playing. /// public void stopimpersonate () {_imperContext.undo (); closehandle (_dupetoken); closehandle (_admintoken); _bclosed = true;}}}