Thursday, September 16, 2004

.NET: Using AD to change a users Password and get Password expiry date

1. Add reference to ActiveDS.tlb (still most AD interfaces are in COM)

2. Following is code from a lot of online sites merged/tested together for a complete working solution.

Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication

http://www.15seconds.com/issue/020730.htm

http://directoryprogramming.net/forums/thread/1531.aspx

Use RoleManager for Windows Authentication in ASP.NET 2.0

// Set the search string along with LDAP path. The search is on username.

// You shouldn't bind as the user whose password you want to change, hence use impersonatable-known-user

string path =
"LDAP://"+"ldapserver"+"/CN="+"username-to-test"+"," + "CN=Users,DC=domain1,DC=main-domain";
try
{
// Create a 'DirectoryEntry' object to search
DirectoryEntry entry = new DirectoryEntry(path, "impersonatable-known-user", "impersonate-known-password",
AuthenticationTypes.ServerBind);
//OR DirectoryEntry entry = new DirectoryEntry(path, domain + "\\" +
impersonatable-known-user, impersonate-known-password,
//AuthenticationTypes.Secure);

Object obj = null;
try
{
//Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}

if (!obj)
{
//user is not authenicated
return false;
}
//user is authenicated

// Create the Directory search instance.
DirectorySearcher search = new DirectorySearcher(entry);

//maybe this line is better --> DirectoryEntry result = new DirectoryEntry(path,
// null, null, AuthenticationTypes.None) 'Bind using existing, open connection

// Get the first search result - search is on username.
SearchResult result = search.FindOne();
// If the username has been found in the LDAP server.

if(null != result)
{
// The result obtained will look like the following:
// CN=group1,CN=group2,DC=domain1,DC=main-domain
// Get the value of 'memberof' from the properties collection
//MSDN Sample: 'System.DirectoryServices.SearchResult'
if (result.Properties.Contains("memberof"))
{
.....

No comments: