private void ChangePassword( string currentPassword, string newPassword, UserPrincipal userPrincipal) { try { // Try by regular ChangePassword method userPrincipal.ChangePassword(currentPassword, newPassword); } catch { if (_options.UseAutomaticContext) { _logger.LogWarning("The User principal password cannot be changed and setPassword won't be called"); throw; } // If the previous attempt failed, use the SetPassword method. userPrincipal.SetPassword(newPassword); _logger.LogDebug("The User principal password updated with setPassword"); } }
protected void administrarContrasenia(UserPrincipal usuario) { try { usuario.ChangePassword(OldPassword.Text.Trim(), ConfirmPassword.Text.Trim()); } catch (InvalidOperationException ioe) { lblErrorPassword.Text = ioe.Message; //lblErrorPassword.Text = "No se ha conservado la entidad de seguridad."; } catch (PasswordException pe) { lblErrorPassword.Text = pe.Message; //lblErrorPassword.Text = "La nueva contraseña no cumple los requisitos de complejidad."; } catch (NotSupportedException nse) { lblErrorPassword.Text = nse.Message; //lblErrorPassword.Text = "La entidad de seguridad no es un usuario."; } catch { lblErrorPassword.Text = "Disculpe, la contraseña no cumple con las directivas."; } }
public static void changePW(String username, String oldPassword, String newPassword) { using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, DOMAIN, username, oldPassword)) { UserPrincipal user = UserPrincipal.FindByIdentity(pc, username); user.ChangePassword(oldPassword, newPassword); } }
private bool ChangeUserPassword(string NewPwd, string oldPwd) { Impersonator impersonator = new Impersonator(); bool result = false; try { impersonator.BeginImpersonation(); string password = ConfigurationSettings.AppSettings["CMICTADPasseord"].ToString(); string domain = ConfigurationSettings.AppSettings["CMICTDomainName"].ToString(); string userName = ConfigurationSettings.AppSettings["CMICTADUser"].ToString(); string container = ConfigurationSettings.AppSettings["CMICTLDAPDomain"].ToString(); SyncADInfoComponent sync = new SyncADInfoComponent(); string loginName = GetLoginName(); using (PrincipalContext context = GetPContext(oldPwd, domain, loginName, container)) { using (UserPrincipal principal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName)) { ////重置用户密码 //result = sync.ChangeUserPassword(loginName, NewPwd); //if (!principal.UserCannotChangePassword) //{ // principal.UserCannotChangePassword = true; //} principal.ChangePassword(oldPwd, NewPwd); //principal.SetPassword(NewPwd); principal.Save(); result = true; } } if (impersonator.IsImpersonated) { impersonator.StopImpersonation(); } } catch (Exception ex) { BaseComponent.Error("用户密码重置: " + ex.Message + "--------" + ex.StackTrace); if (impersonator.IsImpersonated) { impersonator.StopImpersonation(); } } return(result); }
public int ResetPassword(string username, string password, string newpassword) { try { PrincipalContext pcontext = ADUtils.GetPContext(); UserPrincipal userp = UserPrincipal.FindByIdentity(pcontext, username); userp.ChangePassword(password, newpassword); return(1); } catch (Exception e) { throw new UnauthorizedAccessException("Invalid Administrator Credentials, you may need to get your administrator to reset the HAP+ Settings for Active Directory", e); } return(0); }
protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { status.Visible = true; string username = Request.Form["loginname"]; string oldpass = Request.Form["oldpass"]; string newpass = Request.Form["newpass"]; string confpass = Request.Form["confpass"]; if (confpass == newpass && oldpass != newpass && string.Empty != newpass) { string dnsdomain = ConfigurationManager.AppSettings["DomainName"]; if (dnsdomain == null) { dnsdomain = IPGlobalProperties.GetIPGlobalProperties().DomainName; } string searchbase = ConfigurationManager.AppSettings["SearchBase"]; if (searchbase == null) { searchbase = string.Join(",", dnsdomain.Split('.').Select(x => "dc=" + x)); } PrincipalContext context = new PrincipalContext(ContextType.Domain, dnsdomain, searchbase, username, oldpass); UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username); if (user == null) { user = UserPrincipal.FindByIdentity(context, IdentityType.UserPrincipalName, username); } if (user != null) { user.ChangePassword(oldpass, newpass); msg.Text = "Password Changed Successfully!"; } else { msg.Text = "Problem finding username."; } } else { msg.Text = "New Password invalid. It cannot be blank, or the same as your old password."; } } else { status.Visible = false; } }
public bool ChangeUserPassword(string username, string oldPassword, string newPassword, string domain) { try { using (var context = new PrincipalContext(ContextType.Domain, domain, username, oldPassword)) { UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username); user.ChangePassword(oldPassword, newPassword); user.Save(); } return(true); }catch (Exception e) { return(false); } }
public static async Task ChangeUserPassword(UserPrincipal user, string oldPassword, string newPassword) { try { await Task.Run(() => user.ChangePassword(oldPassword, newPassword)); } catch (PasswordException ex) { UnwrapAndRethrowPasswordException(ex); throw; } catch (PrincipalOperationException ex) { UnwrapAndRethrowPasswordException(ex); throw; } }
public static bool ChangePassword(string userName, string domain, string oldPassword, string newPassword) { using (var context = new PrincipalContext(ContextType.Domain, domain)) { PrincipalContext ctx = new PrincipalContext(ContextType.Domain); UserPrincipal user = UserPrincipal.FindByIdentity(ctx, NormalizeUsername(userName)); var userProperties = new Dictionary <string, object>(); if (user == null) { LogManager.GetLogger(typeof(ActiveDirectoryHelper)) .Debug($"User '{userName}'(normalized: '{NormalizeUsername(userName)}) not found under '{domain}' domain"); return(false); } user.ChangePassword(oldPassword, newPassword); return(true); } }
/// <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; } }
public bool ChangeLocalPassword(string userName, string oldPassword, string newPassword) { // Local security policy as of 1/29/2020 at pomps is that password cannot be changed more // than 1 time in a 24 hour period. try { using (PrincipalContext context = new PrincipalContext(ContextType.Machine)) { UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName); if (user == null) { throw new ApplicationException("user " + userName + " not found"); } else { user.ChangePassword(oldPassword, newPassword); } } } catch (Exception ex) { SetError(ex.Message); } return(!IsError); }
public bool ChangePassword(string Username, string Password, string NewPassword) { 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; try { userPrincipal.ChangePassword(Password, NewPassword); userPrincipal.Save(principalContext); result = true; } catch (Exception ex) { this.mvarsError = ex.Message; result = false; } finally { userPrincipal.Dispose(); principalContext.Dispose(); } return(result); }
public string Get(string username, string oldpassword, string newpassword) { // https://b606mgt/api/ADUserChangePassword?username=daves&oldpassword=myoldpassword&newpassword=mynewpassword // MUST be properly URL encoded strings for username, old and new password UserPrincipal up = null; PrincipalContext pc = null; // Validate user exists try { pc = new PrincipalContext(ContextType.Domain); up = UserPrincipal.FindByIdentity(pc, username); if (up == null) { return("User does not exist!"); } } catch (Exception ex) { return("Error: " + ex.Message.ToString()); } // Validate user is enabled (not disabled) try { if (up.Enabled == false) { return("User account is disabled"); } } catch (Exception ex) { return("Error: " + ex.Message.ToString()); } // Changer user password try { up.ChangePassword(oldpassword, newpassword); return("Successfully changed password"); } catch (PasswordException px) { return("Password Error: " + px.Message.ToString()); } catch (Exception ex) { return("Error: " + ex.Message.ToString()); } // TODO - do NOT RUN - If user is not valid, it will change your password, not the user name you looked up /* * using (var context = new PrincipalContext(ContextType.Domain)) { * using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username)) { * //user.SetPassword("newpassword"); * // or * //user.ChangePassword("oldPassword", "newpassword"); * //user.Save(); * return "Success"; * } */ /* * * namespace PasswordChanger * { * using System; * using System.DirectoryServices.AccountManagement; * * class Program * { * static void Main(string[] args) * { * ChangePassword("domain", "user", "oldpassword", "newpassword"); * } * * public static void ChangePassword(string domain, string userName, string oldPassword, string newPassword) * { * try * { * using (var context = new PrincipalContext(ContextType.Domain, domain)) * using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName)) * { * user.ChangePassword(oldPassword, newPassword); * } * * } * catch (Exception ex) * { * Console.WriteLine(ex); * } * } * } * } */ }
private void button1_Click(object sender, EventArgs e) { String user = getUser(); String oldpass = tbOldPass.Text.Trim(); String newpass = tbNewPassword.Text.Trim(); bool isAdmin = isUserAdmin(user); if (isAdmin) { user = tbUser.Text.Trim(); } if (newpass != tbRepeat.Text.Trim()) { MessageBox.Show("Passwords do not match.", "Error"); return; } if (newpass == "") { MessageBox.Show("New password can't be blank.", "Error"); return; } if (newpass.Length > 10) { MessageBox.Show("New password can't be more than 10 characters.", "Error"); return; } //need more password checks PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DOMAIN1"); if (!isAdmin) { if (!pc.ValidateCredentials(user, oldpass)) { MessageBox.Show("Old password is invalid on Windows domain.", "Error"); return; } if (VerifyUserPass(user, oldpass) != "") { MessageBox.Show("Old password is invalid on AS400.", "Error"); return; } } UserPrincipal userAccount = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, user); if (userAccount == null) { MessageBox.Show("Windows account does not exist.", "Error"); return; } if (isAdmin) { //change password if (userAccount != null) { userAccount.SetPassword(newpass); userAccount.Enabled = true; userAccount.Save(); } //change on as400 and enable if we are admin ExecCommand($"CHGUSRPRF USRPRF({user}) PASSWORD({newpass}) STATUS(*ENABLED)"); MessageBox.Show("Password successfully changed and accounts enabled, user must log out and back in.", "Success!"); } else { try { userAccount.ChangePassword(oldpass, newpass); userAccount.Save(); ChangePassword(user, oldpass, newpass); MessageBox.Show("Password successfully changed. You must log out and back in.", "Success!"); //WTSDisconnectSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false); Process.Start("C:\\Windows\\system32\\shutdown.exe", "/r /t:01"); Application.Exit(); } catch (PasswordException exception) { MessageBox.Show(exception.Message, "Invalid Password"); } } }
protected void Save_Click(object sender, EventArgs e) { try { if (inpOldPassword.Value.Trim() == "" || inpNewPassword.Value.Trim() == "" || inpConfirmPassword.Value.Trim() == "") { divValidation.InnerHtml = "<br/><font color=red>You cannot leave any blank values.</font>"; } else if (inpNewPassword.Value != inpConfirmPassword.Value) { divValidation.InnerHtml = "<br/><font color=red>The passwords that you entered did not match.</font>"; } else { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, usrDomain, usrname, inpOldPassword.Value)) { UserPrincipal user = new UserPrincipal(ctx); user = UserPrincipal.FindByIdentity(ctx, usrname); //Change the password user.ChangePassword(inpOldPassword.Value, inpNewPassword.Value); user.Save(); pnlMain.Visible = false; pnlSuccessfull.Visible = true; } } } catch (Exception ex) { string stroPError = "The user name or password is incorrect."; string stroPError2 = "Logon failure: unknown user name or bad password."; string stroPError3 = "System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"; string strErrType = ex.GetType().ToString(); string errMsg = ex.Message.Trim(); string errMsgInner = ""; if (ex.InnerException != null) { errMsgInner = ex.InnerException.ToString().Trim(); } if (errMsg == stroPError) { divValidation.InnerHtml = "<br/><font color=red>The old password is incorrect.</font>"; divError.InnerHtml = ""; } else if (errMsg == stroPError2) { divValidation.InnerHtml = "<br/><font color=red>The old password is incorrect.</font>"; divError.InnerHtml = ""; } else if (errMsgInner == stroPError3) { divValidation.InnerHtml = "<br/><font color=red>Access is Denied. You cannot change your password.</font>"; divError.InnerHtml = ""; } else if (strErrType.Trim() == "System.DirectoryServices.AccountManagement.PasswordException") { divValidation.InnerHtml = "<br/><font color=red>The password does not meet the password policy requirements. Minimum password length is 8 characters. Password history requirements - the last 6 passwords are remembered and cannot be reused.</font>"; divError.InnerHtml = ""; } else { divValidation.InnerHtml = ""; divError.InnerHtml = "<br/>" + ex.Message; divError.InnerHtml += "<br/>" + ex.GetType(); divError.InnerHtml += "<br/>" + ex.InnerException; divError.InnerHtml += "<br/>Domain: " + usrDomain; } } }