Tuesday, August 4, 2009

LDAP Password Change in C# over internet




One of the recent challanges we had is to change the LDAP password over internet. The scenario
Application hosted to change password : ASP.Net 2.0 hosted in IIS 6.0
Domain : Exposed Internet (not with in Domain)
LDAP server : with in Intranet domain
Requirement is to change the password when some one logs from internet and change the password.
I have used the below code to make it possible
This method will return true if the password change is success

private bool ChangePassword(string strUserName, string strOldPassword, string strNewPassword)
{
const long ADS_OPTION_PASSWORD_PORTNUMBER = 6;
const long ADS_OPTION_PASSWORD_METHOD = 7;
const int ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0;
const int ADS_PASSWORD_ENCODE_CLEAR = 1;
string strPort = "389";
int intPort;
intPort = Int32.Parse(strPort);

try
{
string strUserString = "partnermind" + @"\" + strUserName.Trim();
//Replace XXX.XXX.XXX.XXX with your LDAP server IP
DirectoryEntry entry = new DirectoryEntry("LDAP://XXX.XXX.XXX.XXX", strUserString, strOldPassword, AuthenticationTypes.Secure AuthenticationTypes.Sealing AuthenticationTypes.ServerBind);
DirectorySearcher search = new DirectorySearcher(entry);
string strFilter = "(SAMAccountName=" + strUserName + ")";
search.Filter = strFilter;
SearchResult result = search.FindOne();
DirectoryEntry user = result.GetDirectoryEntry();
//Setting up the beloow 2 properties is very important. Other wise it will now rork
user.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_PORTNUMBER, intPort });
user.Invoke("SetOption", new object[] { ADS_OPTION_PASSWORD_METHOD, ADS_PASSWORD_ENCODE_CLEAR });
user.Invoke("ChangePassword", new object[] {strOldPassword, strNewPassword });
user.CommitChanges();
}
catch (Exception exception)
{
lblError.Visible = true;
lblError.Text = "There is an error while changing password.";
ManageError.WriteError("Change password failed for"+strUserName+"/nUser:"+exception.Message);
return false;
}
return true;
}



Hope this helps every one.. Happy Coding:)

1 comment:

Anonymous said...

Thank you very much for this post, finally you saved me from put a 3 months work in the garbage because of some stupid firewall rules!