public bool checkUser(string Domain, string username, string pwd) { string sDomain = "LDAP://172.22.14.40/"; string sDefaultOU = "ou=users,ou=system"; string sServiceUser = @"uid=admin,ou=system"; string sServicePassword = "******"; PrincipalContext oPrincipalContext = new PrincipalContext (ContextType.Domain, sDomain, sDefaultOU, sServiceUser, sServicePassword); UserPrincipal usr = UserPrincipal.FindByIdentity(oPrincipalContext, IdentityType.SamAccountName, "pnunez"); if (usr != null) { if (usr.Enabled == false) { usr.Enabled = true; } usr.Save(); usr.Dispose(); } oPrincipalContext.Dispose(); return(true); }
/// <summary> ///A test for UserPrincipal Constructor ///</summary> public void UserPrincipalConstructorTest() { UserPrincipal user = new UserPrincipal(domainContext); user.Dispose(); //Assert.Inconclusive("TODO: Implement code to verify target"); }
/// <summary> /// Creates a user account in activer directory domain. /// </summary> /// <param name="firstName">first name for user</param> /// <param name="middleName">middle name for user</param> /// <param name="lastName">last name for user</param> /// <param name="loginName">user account login name</param> /// <param name="password">user account password</param> /// <param name="email">user emailid</param> /// <param name="userCompanyName">user company name</param> public void CreateUserAccount(string firstName, string middleName, string lastName , string loginName, string email, string userCompanyName) { try { UserPrincipal userEntry = new UserPrincipal(activeDirectoryDomain); userEntry.GivenName = firstName; userEntry.MiddleName = middleName; userEntry.Surname = lastName; userEntry.Name = string.Format("{0} {1} {2}", firstName, middleName, lastName); userEntry.DisplayName = string.Format("{0} {1} {2}", firstName, middleName, lastName); userEntry.SamAccountName = loginName; userEntry.UserPrincipalName = loginName; userEntry.PasswordNeverExpires = true; userEntry.EmailAddress = email; userEntry.Description = string.Format("Employee of company {0}", userCompanyName); userEntry.Enabled = true; userEntry.Save(); userEntry.Dispose(); } catch (PrincipalExistsException px) { throw new TerminalServerLoginIdExistsException("User login name already exists.", px); } catch (Exception ex) { //throw new ApplicationException("User account does not exists."); throw ex; } }
//Searches specified OU against AD and finds all enabled user accounts public List <string> GetADUserList(string domain) { List <string> ADActiveUserList = new List <string>(); PrincipalContext context = GetContext(); if (context != null) { UserPrincipal userPrin = new UserPrincipal(context); PrincipalSearcher searcher = new PrincipalSearcher(userPrin); foreach (var result in searcher.FindAll()) { DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry; UserPrincipal u = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, de.Properties["samAccountName"].Value.ToString()); if (u.Enabled == true) { if (u.SamAccountName != AppAuth["Username"]) { ADActiveUserList.Add(u.SamAccountName); } } } searcher.Dispose(); userPrin.Dispose(); context.Dispose(); } ADActiveUserList.Sort(); return(ADActiveUserList); }
private LocalPrincipalData InnerCreateUser(string userName) { string rvUserName = null; string rvPassword = null; LocalPrincipalData rv = null; using (var context = new PrincipalContext(ContextType.Machine)) { bool userSaved = false; ushort tries = 0; UserPrincipal user = null; try { do { try { if (user != null) { user.Dispose(); } rvPassword = Membership.GeneratePassword(8, 2).ToLowerInvariant() + Membership.GeneratePassword(8, 2).ToUpperInvariant(); user = new UserPrincipal(context, userName, rvPassword, true); user.DisplayName = "Warden User " + userName; user.Save(); userSaved = true; } catch (PasswordException ex) { log.DebugException(ex); } ++tries; } while (userSaved == false && tries < 5); if (userSaved) { rvUserName = user.SamAccountName; foreach (string userGroupName in this.wardenUserGroups) { AddUserToGroup(rvUserName, userGroupName); } rv = new LocalPrincipalData(rvUserName, rvPassword); } } finally { if (user != null) { user.Dispose(); } } } return(rv); }
//Unlocks account returns message depending on success?failure public string UnlockAccount(string searchQuery) { string accountUnlockStatus = string.Empty; PrincipalContext context = GetContext(); if (context != null) { UserPrincipal userResult = UserPrincipal.FindByIdentity(context, searchQuery); try { if (userResult != null) { userResult.UnlockAccount(); accountUnlockStatus = "Account was unlocked."; } } catch (PrincipalOperationException pEx) { accountUnlockStatus = pEx.Message; } userResult.Dispose(); context.Dispose(); } return(accountUnlockStatus); }
public void Delete() { #if WINDOWS_USER_ACCOUNT_SUPPORT using (var principalContext = new PrincipalContext(ContextType.Machine)) { UserPrincipal principal = null; try { principal = UserPrincipal.FindByIdentity(principalContext, IdentityType.Name, UserName); if (principal == null) { Console.WriteLine($"The Windows User Account named {UserName} doesn't exist, nothing to do..."); return; } Console.WriteLine($"The Windows User Account named {UserName} exists, deleting..."); principal.Delete(); } finally { principal?.Dispose(); } } #endif }
private void btnEditUser_Click(object sender, EventArgs e) { if (lbUsers.SelectedItem == null) { MessageBox.Show("Please select a user"); return; } UserPrincipal insUserPrincipal = (UserPrincipal)lbUsers.SelectedItem; frmProperties insFrmProperties = new frmProperties(insUserPrincipal, ActionTypes.Save); insFrmProperties.ShowDialog(); if (insFrmProperties.DialogResult == DialogResult.OK) { try { insUserPrincipal.Save(); insUserPrincipal.Dispose(); MessageBox.Show("User updated."); } catch (Exception ex) { MessageBox.Show(ex.Message); } ListUsers(); } }
//Reset user account password, returns message depending on success?failure public string ResetPassword(string searchQuery, string password) { string passwordStatusMessage = String.Empty; PrincipalContext context = GetContext(); if (context != null) { UserPrincipal userResult = UserPrincipal.FindByIdentity(context, searchQuery); if (userResult != null && userResult.SamAccountName != AppAuth["Username"]) { try { userResult.SetPassword(password); passwordStatusMessage = "Password was successfully changed."; } catch (Exception e) { passwordStatusMessage = e.Message; } userResult.Dispose(); } else { passwordStatusMessage = "The password for this account cannot be reset via this application."; } context.Dispose(); } return(passwordStatusMessage); }
/// <summary> /// Makes user with given login name member of group with given name if exists. /// </summary> /// <param name="groupName">group name</param> public void AssignUserGroup(string loginName, string groupName) { // Find user entry by login name UserPrincipal userEntry = UserPrincipal.FindByIdentity(activeDirectoryDomain, IdentityType.SamAccountName, loginName); // Search for group with matching name PrincipalSearchResult <Principal> activeDirectoryGroups = this.ListGroupsByName( this.activeDirectoryDomain, groupName); if (activeDirectoryGroups.Count <Principal>() != 0) { GroupPrincipal group = (GroupPrincipal)activeDirectoryGroups.First <Principal>(); // make user member of group group.Members.Add(userEntry); // save changes group.Save(); group.Dispose(); } else { // throw exception to notify the group does not exists throw new ApplicationException("Domain group not found."); } // dispose the objects userEntry.Dispose(); activeDirectoryGroups.Dispose(); }
public void Delete(string username) { UserPrincipal usr = null; try { pc = GetPrincipalContext(); log.DebugFormat("Attempting to retrieve user {0}", username); usr = UserPrincipal.FindByIdentity(pc, IdentityType.UserPrincipalName, username); if (usr != null) { usr.Delete(); log.InfoFormat("Successfully deleted user {0}", username); } else { log.InfoFormat("Attempted to delete user {0} but could not find the user in Active Directory. Assuming user was manually deleted... continuing...", username); } } catch (Exception ex) { log.ErrorFormat("Failed to delete user {0}. Exception: {1}", username, ex.ToString()); throw; } finally { if (usr != null) { usr.Dispose(); } } }
public byte[] GetPhoto(string username) { UserPrincipal usr = null; try { pc = GetPrincipalContext(); log.DebugFormat("Attempting to retrieve user photo for {0}", username); usr = UserPrincipal.FindByIdentity(pc, IdentityType.UserPrincipalName, username); DirectoryEntry tmp = (DirectoryEntry)usr.GetUnderlyingObject(); if (tmp.Properties["thumbnailPhoto"] != null && tmp.Properties["thumbnailPhoto"].Count > 0) { return(tmp.Properties["thumbnailPhoto"][0] as byte[]); } else { return(null); } } catch (Exception ex) { log.ErrorFormat("Error retrieving user photo for {0}. Exception: {1}", username, ex.ToString()); throw; } finally { if (usr != null) { usr.Dispose(); } } }
public static bool AddUserToGroup(string samAccountName, string groupName, AdAdminConfig config) { if (IfUserExist(samAccountName, config)) { if (!IfUserExistInGroup(samAccountName, groupName, config)) { try { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, config.ServerIpOrDomain, config.AdminAccount, config.AdminPwd); // find the group in question GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName); UserPrincipal user = UserPrincipal.FindByIdentity(ctx, samAccountName); group.Members.Add(user); group.Save(); group.Dispose(); user.Dispose(); ctx.Dispose(); } catch (Exception ex) { return(false); } return(true); } return(false); } return(false); }
public bool IsExpired(string Username) { PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, this.IP_ADDRESS, "CN=" + Username + ",OU=USERS,OU=Vulindlela3," + this.DC, this.ADSMasterUsername, this.ADSMasterPassword); UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, Username); bool result = userPrincipal.AccountExpirationDate < DateTime.Now; userPrincipal.Dispose(); principalContext.Dispose(); return(result); }
/// <summary> /// Delete user account with login name /// </summary> /// <param name="loginName">domain login name</param> public void DeleteAccount(string loginName) { // Find user entry by login name UserPrincipal userEntry = UserPrincipal.FindByIdentity(activeDirectoryDomain, IdentityType.SamAccountName, loginName); userEntry.Delete(); userEntry.Dispose(); }
public string LdapGetCommonName(string firstName, string lastName) { Ldap ldap = Ldap.Instance; PrincipalContext ctx = ldap.GetPrincipalContext; userPrincipal = new UserPrincipal(ctx); searchUser = new PrincipalSearcher(); try { if ((firstName != "" && firstName.Length != 0) && (lastName != "" && lastName.Length != 0)) { userPrincipal.GivenName = firstName; userPrincipal.Surname = lastName; searchUser.QueryFilter = userPrincipal; PrincipalSearchResult <Principal> results = searchUser.FindAll(); foreach (UserPrincipal name in results) { if (!name.Name.Contains("zbc")) { return(name.Name); } } return($"No Account Found."); } } catch (Exception ex) { Debug.WriteLine($"Exception: {ex.Message}"); userInfo = "User not found."; return(userInfo); } finally { if (ctx != null) { ctx.Dispose(); Debug.WriteLine($"Disposed: Context"); } if (userPrincipal != null) { userPrincipal.Dispose(); Debug.WriteLine($"Disposed: User Principal."); } if (searchUser != null) { searchUser.Dispose(); Debug.WriteLine($"Disposed: Search User."); } } return(userInfo); }
/// <summary> /// Agrega un nuevo usuario /// </summary> /// <param name="nombre">Nombre del usuario</param> /// <param name="contraseña">Contraseña</param> /// <param name="descripción">Descripción de usuario</param> public void AgregarUsuario(string nombre, string contraseña, string descripción) { UserPrincipal nuevoUsuario = new UserPrincipal(_dominio); nuevoUsuario.Name = nombre; nuevoUsuario.SetPassword(contraseña); nuevoUsuario.Description = descripción; nuevoUsuario.Save(); nuevoUsuario.Dispose(); }
/// <summary> /// Finds the user asynchronous. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns></returns> /// <exception cref="SecurityAccessDeniedException"> /// There were no valid active directory accounts with the username of: " + username /// or /// Incorrect username or password /// </exception> /// <exception cref="Exception"></exception> public async Task <ApplicationUser> FindUserAsync(string username, string password) { // TODO: put this into web.confog // Find the user within the active directory using (var context = new PrincipalContext( ContextType.Domain, @"ash-dc02.sehnp.nhs.uk:3268", @"DC=sehnp,DC=nhs,DC=uk", @"SEHNP\RemoteDeployService", @"RDS31@Essex#")) { UserPrincipal personPrincipal = null; try { // Find the user in the active directory by using their username personPrincipal = await Task.Run(() => UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username)); // Throw an exception if an account couldn't be found if (personPrincipal == null) { throw new SecurityAccessDeniedException( "There were no valid active directory accounts with the username of: " + username); } // Validate the password using the UPN as the username because the UPN must be unique across the forest // CF-138: NS: 16-06-2016 // Changing this to use sAMAccountName as the UserPrincipalName is not mandatory and can be NULL // see: https://social.technet.microsoft.com/Forums/windowsserver/en-US/0479b81d-07ba-4167-b770-e9db87b2a32b/sam-account-name-vs-upn?forum=winserverDS if (!context.ValidateCredentials(personPrincipal.SamAccountName, password)) { throw new SecurityAccessDeniedException("Incorrect username or password"); } // Return active directory details return(new ApplicationUser { ActiveDirectoryGuid = personPrincipal.Guid.ToString(), ActiveDirectorySid = personPrincipal.Sid.ToString(), ActiveDirectoryEmailAddress = personPrincipal.EmailAddress }); } catch (Exception ex) { throw new Exception(ex.Message); } finally { personPrincipal?.Dispose(); } } }
public void Dispose() { if (_disposed) { return; } _principal.Delete(); _principal.Dispose(); _context.Dispose(); PasswordAsSecureString.Dispose(); _disposed = true; }
/// <inheritdoc /> public void Dispose() { if (identity != null) { identity.Dispose(); } else { var context = userPrincipal.Context; userPrincipal.Dispose(); context.Dispose(); } }
public bool IsExpired(string Username) { PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, VulindlelaFTPServer.Properties.Settings.Default.VulIP, "CN=" + Username.Trim() + ",OU=USERS,OU=Vulindlela3," + VulindlelaFTPServer.Properties.Settings.Default.VulDC, VulindlelaFTPServer.Properties.Settings.Default.VulMasterUser, VulindlelaFTPServer.Properties.Settings.Default.VulMasterPassword); UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, Username); bool result = (userPrincipal.AccountExpirationDate < DateTime.Now); userPrincipal.Dispose(); principalContext.Dispose(); return(result); }
/// <summary> /// Make user account with given login name active or inactive /// </summary> /// <param name="loginName">user domain login name</param> /// <param name="status">true for enable false for disable</param> public void SetAccountStatus(string loginName, bool status) { try { // Find user entry by login name UserPrincipal userEntry = UserPrincipal.FindByIdentity(activeDirectoryDomain, IdentityType.SamAccountName, loginName); userEntry.Enabled = status; userEntry.Save(); userEntry.Dispose(); } catch (Exception ex) { throw new TerminalServerSetAccountStatusFailedException("Failed to set Account Status", ex); } }
public void UpdateUserAttribute(string userPrincipalName, string property, string newValue) { UserPrincipal usr = null; try { if (string.IsNullOrEmpty(userPrincipalName)) { throw new MissingFieldException("Users", "UserPrincipalName"); } if (string.IsNullOrEmpty(property)) { throw new MissingFieldException("Users", "Property"); } log.DebugFormat("Updating user {0} property {1} to {2}...", userPrincipalName, property, newValue); pc = GetPrincipalContext(); usr = UserPrincipal.FindByIdentity(pc, IdentityType.UserPrincipalName, userPrincipalName); if (usr == null) { throw new NoMatchingPrincipalException(userPrincipalName); } DirectoryEntry deEntry = usr.GetUnderlyingObject() as DirectoryEntry; SetPropertyValue(ref deEntry, property, newValue); deEntry.CommitChanges(); log.InfoFormat("Successfully updated user {0} property {1} to {2}.", userPrincipalName, property, newValue); } catch (Exception ex) { log.InfoFormat("Error updating user {0} property {1}.", userPrincipalName, property); throw; } finally { if (usr != null) { usr.Dispose(); } } }
private void btnFindUser2_Click(object sender, RoutedEventArgs e) { try { lbeResults.Clear(); var name = wucActiveDirectory_Picker.Name; var dnsHostName = wucActiveDirectory_Picker.DNSHostName; var defaultNamingContext = wucActiveDirectory_Picker.DefaultNamingContext; // enter AD settings using (PrincipalContext AD = new PrincipalContext(ContextType.Domain, dnsHostName)) { UserPrincipal userPrincipal = new UserPrincipal(AD); UserPrincipal result = default; userPrincipal = SearchBy(userPrincipal, ((ListBoxEditItem)lbeSearchBy.SelectedItem).Content.ToString(), teSearchPattern.Text);;; PrincipalSearcher search = new PrincipalSearcher(userPrincipal); userPrincipal.Dispose(); switch (((ListBoxEditItem)lbeFindCount.SelectedItem).Content.ToString()) { case "FindOne": result = (UserPrincipal)search.FindOne(); search.Dispose(); DisplayResults(result); break; case "FindAll": PrincipalSearchResult <Principal> results = search.FindAll(); search.Dispose(); // TODO(crhodes) // Display Results break; } } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
private void UnlockUser() { // set up domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "CEWA", CurrentUser.UserOU); // find a user UserPrincipal user = UserPrincipal.FindByIdentity(ctx, CurrentUser.UserName); if (user != null) { user.UnlockAccount(); user.Save(); } user.Dispose(); ctx.Dispose(); btnUnlock.Visibility = Visibility.Hidden; DisplayUser(CurrentUser.UserName); }
/// <summary> /// Resets the password for the user /// </summary> /// <param name="userPrincipalName"></param> /// <param name="newPassword"></param> public void ResetPassword(string userPrincipalName, string newPassword) { PrincipalContext pc = null; UserPrincipal up = null; try { pc = new PrincipalContext(ContextType.Domain, this.domainController, this.username, this.password); logger.Debug("Looking to see if user already exists to reset the password: "******"Successfully changed password for " + userPrincipalName); } } catch (PasswordException ex) { this.logger.Error("Error changing password for " + userPrincipalName, ex); throw; } catch (Exception ex) { this.logger.Error("Error changing password for " + userPrincipalName, ex); throw; } finally { if (up != null) { up.Dispose(); } if (pc != null) { pc.Dispose(); } } }
//Searches specified string against AD to find a user account then compiles account info into ADUser class public ADUser DirectorySearch(string searchQuery, string domain) { ADUser user = new ADUser(); PrincipalContext context = GetContext(); if (context != null) { UserPrincipal userResult = UserPrincipal.FindByIdentity(context, searchQuery); if (userResult != null) { PrincipalSearchResult <Principal> groups = userResult.GetGroups(); foreach (Principal p in groups) { if (p is GroupPrincipal) { user.SecurityGroups.Add(p.ToString()); } } PropertyCollection properties = ((DirectoryEntry)userResult.GetUnderlyingObject()).Properties; foreach (object property in properties["proxyaddresses"]) { string p = property.ToString(); user.ProxyAddresses.Add(p); } DirectoryEntry deUser = userResult.GetUnderlyingObject() as DirectoryEntry; DirectoryEntry deUserContainer = deUser.Parent; user.OU = deUserContainer.Properties["distinguishedName"].Value.ToString(); // Console.WriteLine(properties["distinguishedName"].Value.ToString()); user.DisplayName = userResult.DisplayName; user.UserName = userResult.SamAccountName; user.EmailAddress = userResult.EmailAddress; user.LastBadPasswordAttempt = userResult.LastBadPasswordAttempt; user.LastLogon = userResult.LastLogon; user.AccountLocked = userResult.IsAccountLockedOut(); user.AccountLockoutTime = userResult.AccountLockoutTime; user.UserCannotChangePassword = userResult.UserCannotChangePassword; userResult.Dispose(); context.Dispose(); } } return(user); }
public void ResetPassword(string username, string newClearTextPassword) { UserPrincipal usr = null; try { log.DebugFormat("Attempting to reset password for user {0}", username); if (string.IsNullOrEmpty(username)) { throw new MissingFieldException("Users", "username"); } if (string.IsNullOrEmpty(newClearTextPassword)) { throw new MissingFieldException("Users", "Password"); } pc = GetPrincipalContext(); usr = UserPrincipal.FindByIdentity(pc, IdentityType.UserPrincipalName, username); if (usr == null) { throw new NoMatchingPrincipalException(username); } usr.SetPassword(newClearTextPassword); log.InfoFormat("Successfully reset password for {0}", username); } catch (Exception ex) { log.ErrorFormat("Error resetting password for {0}. Exception {1}.", username, ex.ToString()); throw; } finally { if (usr != null) { usr.Dispose(); } } }
/// <summary> /// Verifies the user. /// </summary> /// <param name="guidValue">The unique identifier value.</param> /// <returns></returns> /// <exception cref="SecurityAccessDeniedException">No valid active directory accounts had the GUID value</exception> /// <exception cref="Exception"></exception> private string VerifyUser(string guidValue) { // TODO: put this into web.confog // Establish domain credentials using (var context = new PrincipalContext( ContextType.Domain, @"ash-dc02.sehnp.nhs.uk:3268", @"DC=sehnp,DC=nhs,DC=uk", @"SEHNP\RemoteDeployService", @"RDS31@Essex#")) { UserPrincipal personPrincipal = null; try { _log.DebugFormat("Searching for user with GUID: {0}", guidValue); // Find the Active Directory GUID personPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.Guid, guidValue); // Is the person in the Active Directory? If not they will suffer a painful death OR throw an exception if (personPrincipal == null) { throw new SecurityAccessDeniedException( "No valid active directory accounts had the GUID value"); } _log.DebugFormat("Found user SID {0}", personPrincipal.Sid); _log.DebugFormat("Active Directory Account for: {0}", personPrincipal.DistinguishedName); // Return the SID as base 64 encoded value return(Convert.ToBase64String(Encoding.UTF8.GetBytes(personPrincipal.Sid.ToString()))); //return personPrincipal.Sid.ToString(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { personPrincipal?.Dispose(); } } }
/// <summary> /// Set the password for user in domain /// </summary> /// <param name="loginName">domain user name</param> /// <param name="oldPassword">old password</param> /// <param name="password">new password</param> public void SetPassword(string loginName, string oldPassword, string password) { try { // Find user entry by login name UserPrincipal userEntry = UserPrincipal.FindByIdentity(activeDirectoryDomain, IdentityType.SamAccountName, loginName); userEntry.ChangePassword(oldPassword, password); userEntry.Dispose(); } catch (PasswordException px) { throw new InvalidPasswordException("Invalid Password", px); } catch (Exception ex) { throw ex; } }