Active Directory PrincipalContext.ValidateCredentials domain disambiguation

落花浮王杯 提交于 2019-11-29 23:01:00

问题


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);
        }
    }

回答1:


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.




回答2:


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.




回答3:


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;
        }
    }



回答4:


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.



来源:https://stackoverflow.com/questions/9473314/active-directory-principalcontext-validatecredentials-domain-disambiguation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!