Part 5 Changing the Password

For the purposes of this example I am using mydomain.local to represent my domain name. Please insert your own domain name instead.

You will also require a user account capable of editing active directory. In this example I am using an account called AresAdmin which has a password of ‘123456789012345’.

Substitute the details of whichever account you decide to use in the following code.

The possibility of using this system to re-enable a disabled account by inserting code such as “user.Enabled = true;” was rejected due to there being good reasons why an account may be disabled.

The class randomly generates a password and then replaces certain characters with others, mainly to avoid confusion when using older till printers and fonts which show little difference between an ‘l’ and a ‘1’. Feel free to remove the following lines if this is unneeded:

NewPassword = NewPassword.Replace(“O”, “0”);

NewPassword = NewPassword.Replace(“l”, “1”);

Create the class that will change the user’s password.

Copy the method used to create the Globals.cs class but this time call it ‘ChangePassword.cs’.

Change the code inside ChangePassword.cs to the following:

using System;
using System.DirectoryServices.AccountManagement;
using System.Security;
using System.Runtime.InteropServices;

namespace Acre
{
class ChangePassword
{
public string PassWordReset(string CardReaderValue)
{
string userName = null;
string password = null;
string passwordstring = null;

try
{
#region payload

PrincipalContext context = new PrincipalContext(ContextType.Domain, “mydomain.local”, “AresAdmin”, “123456789012345”);

UserPrincipal user = UserPrincipal.FindByIdentity(context, System.DirectoryServices.AccountManagement.IdentityType.SamAccountName, CardReaderValue);

//Generate random password

String NewPassword = System.Web.Security.Membership.GeneratePassword(7, 1);
NewPassword = NewPassword.Replace(“O”, “0”);
NewPassword = NewPassword.Replace(“l”, “1”);
NewPassword = NewPassword + “8”;

//Reset User Password

user.SetPassword(NewPassword); //Unremark this line to make it change passwords again!!!!!!

//Force user to change password at next logon

user.ExpirePasswordNow();
user.Save();

return NewPassword;
#endregion
}

catch (Exception epass)
{
Globals.errorCode = epass.ToString();
return “There is a problem setting a new password”;
}
}

About the author: Author

Leave a Reply