Search code examples
c#active-directorydirectoryservices

System.DirectoryServices.AccountManagement bootstrapping myself


I'm trying to bootstrap myself up on the System.DirectoryServices.AccountManagement namespace in order to solve another issue I'm having. In net i want to toggle the "ChangePasswordOnNextLogon" flag in ad and this namespace made it look easy.

So I tried using it with the same users and passwords that I use to login using the AdMembershipProvider.

PrincipalContext oPrincipalContext = 
   new PrincipalContext(ContextType.Domain, "10.1.XXX.XXX", "DC=XXXXXXXX,DC=ORG",
                        ContextOptions.SimpleBind, AUserThatWorks, APasswordThatWorks);

UserPrincipal oUserPrincipal = 
    UserPrincipal.FindByIdentity(oPrincipalContext, AdUserName);

// we need to see if they can authenticate before changing password,so we have to turn this off manually. - EWB
oUserPrincipal.RefreshExpiredPassword();

bool b = oPrincipalContext.ValidateCredentials( AdUserName, AdPassword );

if (!b)
   oUserPrincipal.ExpirePasswordNow();

return b;

But when it gets to FindByIdentity I get a "bad user or password" error.

Since the user works elsewhere, I figure it's gotta be one of the other parameters to get principal context. Anyone got any Hints for me? I tried putting LDAP infront of the URL but then it failed to connect. I'm stumped.

Thanks,

Cal-


Solution

  • Try simplifying your PrincipalContext line:

    PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, "XXXXXX.org", AUserThatWorks, PasswordThatWorks);
    

    This assumes your domain is XXXXXXX.org. You can also try putting your domain in front of your username: "XXXXXX.org\username".