使用AD的服务帐户和用户帐户凭据连接到Active Directory以登录(在我的产品中)

时间:2019-03-18 18:54:33

标签: c# .net active-directory ldap

我当前正在使用Directory Searcher来根据AD对用户进行身份验证。

  DirectoryEntry adsEntry = new DirectoryEntry(ConfigurationManager.AppSettings["ADConnectionString"], username, password, System.DirectoryServices.AuthenticationTypes.Secure);
  DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry);

  adsSearcher.Filter = "(sAMAccountName=" + _userName + ")";

  SetPropertiesToLoad(ref adsSearcher);


  SearchResult adsSearchResult = adsSearcher.FindOne();
  Logger.Debug("After adsSearcher.FindOne() success");

  if (!ExtractPropertiesReceivedFromAD(adsSearchResult, ref emailAddress, ref _name, username, ref errorMessage))
                return false;

这对于许多AD设置来说都可以正常工作,但是最近我遇到1个AD不允许连接到它的情况。

我的客户说他们已经安装了LDAP身份验证,因此如果不提供服务帐户凭据,我将无法直接查询AD。

因此,在这种情况下,要使用LDAP与AD连接,我需要1个凭据,然后发布该凭据以验证用户身份,则需要他自己的用户名/密码。

现在我如何在DirectorySearcher中适应这种情况?

1 个答案:

答案 0 :(得分:0)

这是我使用系统证书绑定到LDAP目录,搜索提供的用户ID,然后验证提供的用户证书的功能。要将功能与Active Directory一起使用,“ strUIDAttr”是sAMAccountName。

protected string ldapAuthTest(string strLDAPServer, string strSuppliedUser, string strSuppliedPwd, string strSystemUID, string strSystemPwd, string strLDAPUserBase, string strUIDAttr)
{
    strSuppliedUser = strSuppliedUser.Trim();
    string strResults = "";
    string strLDAPUserHost = strLDAPServer + strLDAPUserBase;

    // Establish LDAP connection and bind with system ID
    System.DirectoryServices.DirectoryEntry dirEntry = new System.DirectoryServices.DirectoryEntry();
    dirEntry.Path = strLDAPUserHost;
    dirEntry.Username = strSystemUID;
    dirEntry.Password = strSystemPwd;

    //dirEntry.AuthenticationType = System.DirectoryServices.AuthenticationTypes.None;
    dirEntry.AuthenticationType = System.DirectoryServices.AuthenticationTypes.SecureSocketsLayer;
    try
    {
        dirEntry.RefreshCache();

        // Search directory for the user logging on
        string strLDAPFilter = "(&(" + strUIDAttr + "=" + strSuppliedUser + "))";
        System.DirectoryServices.DirectorySearcher ldapSearch = new System.DirectoryServices.DirectorySearcher(dirEntry);
        ldapSearch.ServerTimeLimit = new TimeSpan(0, 0, 30);


        ldapSearch.Filter = strLDAPFilter;
        ldapSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;

        System.DirectoryServices.SearchResultCollection searchResults = ldapSearch.FindAll();


        if (searchResults.Count == 1)
        {
        string strLogonUserBase = searchResults[0].GetDirectoryEntry().Path;
        // get rid of strLDAPServer from directory entry path
        string strLogonUserFQDN = strLogonUserBase.Replace(strLDAPServer, "");
        dirEntry.Close();

        // Attempt to bind as the user
        System.DirectoryServices.DirectoryEntry userAuthAttempt = new System.DirectoryServices.DirectoryEntry();
        userAuthAttempt.Path = strLDAPUserHost;
        userAuthAttempt.Username = strLogonUserFQDN;
        userAuthAttempt.Password = strSuppliedPwd;
        //userAuthAttempt.AuthenticationType = System.DirectoryServices.AuthenticationTypes.None;
        userAuthAttempt.AuthenticationType = System.DirectoryServices.AuthenticationTypes.SecureSocketsLayer;
        try
        {
            userAuthAttempt.RefreshCache();
            userAuthAttempt.Close();
            strResults = "<td><font color='green'>User " + UserName.Value + " has authenticated successfully.</font></td>";
        }
        catch (Exception e)
        {
            string strAuthError = e.Message;
            string strLockedOut = "A constraint violation occurred.\r\n";
            string strBadPwd = "Logon failure: unknown user name or bad password.\r\n";
            string strNSAccountLock = "The server is unwilling to process the request.\r\n";
            if (String.Compare(strAuthError, strBadPwd) == 0)
                strResults = "<td><font color='red'>Logon failure for user " + UserName.Value + " - password is invalid.</font></td></tr>"; ;
            }
            else if (String.Compare(strAuthError, strLockedOut) == 0)
            {
            strResults = "<td><font color='red'>Logon failure for user " + UserName.Value + " - account is locked out.</font></td>"; ;
            }
            else if (String.Compare(strAuthError, strNSAccountLock) == 0)
            {
            strResults = "<td><font color='red'>Logon failure for user " + UserName.Value + " - password has expired.</font></td>"; ;
            }
            else
            {
            strResults = "<td><font color='red'>Logon failure for user " + UserName.Value + " (" + strLogonUserFQDN + ") :" + strAuthError + "</font></td>"; ;
            }
        }
        }
        else if (searchResults.Count > 1)
        {
        strResults = "<td><font color='red'>Account " + UserName.Value + " was found in the directory " + searchResults.Count + " times. Please contact the Help Desk to have this issue corrected.</font></td>"; ;
        }
        else
        {
        strResults = "<td><font color='red'>Account " + UserName.Value + " was not found in the directory.</font></td>"; ;
        }
        return strResults;
    }
    catch(Exception e)
    {
        string strAuthError = e.Message;
        string strConnectFail = "The server is not operational.\r\n";
        if (String.Compare(strAuthError, strConnectFail) == 0)
        {
        strResults = "<td><font color='red'>Transient connection failure, please try again.</font></td>"; ;
        }
        else
        {
        strResults = "<td><font color='red'>Transient failure (" + strAuthError + "), please try again.</font></td>";
        }
        return strResults;
    }
}