【问题标题】:Active Directory PrincipalContext.ValidateCredentials domain disambiguationActive Directory PrincipalContext.ValidateCredentials 域消歧
【发布时间】:2012-03-17 09:58:29
【问题描述】:

我正在处理两个域 - 一个是受信任域。一个域上可能有一个 JohnSmith,另一个域上可能有另一个 JohnSmith。这两个人都需要登录我的应用程序。

我的问题:我传入的域无关紧要 - 此代码返回 true! 我如何知道哪个 JohnSmith 正在登录?

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

【问题讨论】:

    标签: c# active-directory multiple-domains


    【解决方案1】:

    您始终可以检索已使用登录的用户的完整 DN

    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
    

    在后续调用 ValidateCredentials 时使用 up.SamAccountName,包括域名 - 毕竟您不能有 2 个用户使用相同的 sAMAccountName 登录!

    DistinguishedName 肯定会告诉您是哪个 JohnSmith 登录的。

    【讨论】:

      【解决方案2】:

      如果域中包含不同的电子邮件地址,则接受的答案将失败。示例:

      Domain = Company
      
      User1 = employee@department1.com (under company Domain)
      
      User2 = employee2@Department2.com (under company Domain)
      

      提供的答案将使用以下方法返回 false:

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

      跨域包含用户的正确方法是:

      string userPrincipalName = userName + "@" + domain;
      

      如果没有 .com 部分,它会在该域中搜索用户,而不是在全局域中搜索电子邮件。

      【讨论】:

        【解决方案3】:

        根据 JPBlanc 的回答,我重写了我的代码。我还添加了一个 try/catch 以防传入虚假域。

            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】:

          ValidateCredentialsuserPrincipalName 一起使用,您也许可以尝试构建第一个参数(用户名),结合登录名和域来创建用户名 JohnSmith@dom1.comJohnSmith@dom2.com

          【讨论】:

            猜你喜欢
            • 2017-01-27
            • 1970-01-01
            • 1970-01-01
            • 2020-07-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-05-27
            相关资源
            最近更新 更多