Question

I'm dealing with two domains - one is a trusted domain. There may be a JohnSmith on one domain and another JohnSmith on the other. Both of these people need to log into my application.

My problem: it doesn't matter which domain I pass in - this code returns true! How do I know which JohnSmith is logging in?

    static public bool CheckCredentials(
        string userName, string password, string domain)
    {
        using (var context = new PrincipalContext(ContextType.Domain, domain))
        {
            return context.ValidateCredentials(userName, password);
        }
    }
Was it helpful?

Solution

The ValidateCredentials works with userPrincipalName you perhaps can try to build the first parameter (username) combining the login and the domain to create the username JohnSmith@dom1.com versus JohnSmith@dom2.com.

OTHER TIPS

You can always retrieve the full DN of the user who has logged in using

UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
up.UserPrincipalName // shows user@domain.com
up.DistinguishedName // shows CN=Surname,OU=group,DC=domain,DC=com
up.SamAccountName    // shows login name

Use the up.SamAccountName to subsequent calls to ValidateCredentials including the domain name - you can't have 2 users who log in using the same sAMAccountName after all!

The DistinguishedName will definitely show you which JohnSmith logged in.

Based on JPBlanc's answer, I've re-written my code. I've also added a try/catch in case a bogus domain is passed in.

    static public bool CheckCredentials(
        string userName, string password, string domain)
    {
        string userPrincipalName = userName + "@" + domain + ".com";

        try
        {
            using (var context = new PrincipalContext(ContextType.Domain, domain))
            {
                return context.ValidateCredentials(userPrincipalName, password);
            }
        }
        catch // a bogus domain causes an LDAP error
        {
            return false;
        }
    }

The accepted answer will fail with Domains that contain different email addresses within them. Example:

Domain = Company

User1 = employee@department1.com (under company Domain)

User2 = employee2@Department2.com (under company Domain)

The provided answer will return false using:

userName = "employee";
domain = "company";
string userPrincipalName = userName + "@" + domain + ".com";

The correct way to encompass users across domains is:

string userPrincipalName = userName + "@" + domain;

without the .com portion it searches the user AT that domain instead of searching for an email within a global domain.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top