Nick Bedford
Nick Bedford

Reputation: 4435

Full AD domain name from partial

I'm writing an application that can use Windows identities for login authentication instead of username and password, but I want to add a verification function to confirm that a username exists either locally or in the domain's Active Directory service, not unlike Outlook's "Check Names" button.

So if the administrator begins creating a new user and types in mfd\john.smith and clicks Verify it looks does the verification and allows the user to be created.

While I can do that just fine using the DirectorySearcher class, the problem lies in the domain name. Here we have a domain name that is technically "mfd.local" but Environment.UserDomainName and usernames are usually entered as only MFD\username. When I try to use the DirectorySearcher method, it throws an exception saying "a referral was returned by the server" with no information as to the referral.

When I manually change it to mfd.local\username the searcher works. When I set DirectorySearcher.ReferralChasing to All it still doesn't work.

Is there a way of accepting the short version of a domain name in doing an LDAP search?

Upvotes: 0

Views: 152

Answers (1)

Nick Bedford
Nick Bedford

Reputation: 4435

And just like that I've found the solution! It accepts the shorter domain name MFD where the full domain name is mfd.local.

private static bool DomainUserExists(string domain, string username)
{
    try {
        var context = new PrincipalContext(ContextType.Domain, domain);
        var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
        return userPrincipal != null;
    }
    catch (Exception exc)
    {
        // handle if necessary
        return false;
    }
}

Upvotes: 0

Related Questions