无法通过LDAP连接

时间:2018-05-24 08:08:22

标签: c# asp.net active-directory ldap asp.net-web-api2

我正在使用ASP.NET技术开发WEB API项目。此Web API需要从AD Active Directory检查用户,使用LDEP://

作为域身份验证
    [HttpGet]
    public IHttpActionResult ListProperties(string domainName, string userName, string password)
    {
        try
        {
            using (DirectoryEntry dEntry = new DirectoryEntry("LDAP://" + domainName, userName, password))
            {
                DirectorySearcher dSearcher = new DirectorySearcher(dEntry)
                {
                    Filter = "(&(objectClass=user)(mail=" + userName + "))"
                };
                SearchResult sResult = dSearcher.FindOne();
                Dictionary<string, string> resultDictionary = new Dictionary<string, string>
                {
                    {"Name", GetProperty(sResult,"cn")},
                    {"Email", GetProperty(sResult,"mail")}
                };

                return Ok(resultDictionary.ToList());
            }
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }


    private string GetProperty(SearchResult searchResult, string propertyName)
    {
        if (searchResult.Properties.Contains(propertyName))
        {
            return searchResult.Properties[propertyName][0].ToString();
        }
        return string.Empty;
    }

所以我用ajax调用此方法仅用于测试

$(document).ready(function () { 


    $.ajax({
        type: "GET",
        url: "../api/xxxxxxx/ListProperties",
        data: { domainName: "mydomain.xxx.xx", userName: "MyUsername", password: "MyPassword" },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) { console.log(JSON.stringify(data)); },
        failure: function (data) { console.log(0); },
        error: function (data)   { console.log(1); }
    });
});

不幸的是,我总是收到错误请求或以下错误

System.Runtime.InteropServices.COMException HResult=0x8007203A Message=The server is not operational.

您能否向我提供如何解决此问题的指南,因为我之前从未使用过安全编程。

1 个答案:

答案 0 :(得分:0)

错误意味着它没有从域控制器获得任何响应。可能是域控制器没有网络连接。

要测试网络连接,您可以在PowerShell中尝试使用domainName变量中的内容代替&#34; domain.com&#34;

(New-Object Net.Sockets.TcpClient).Connect("domain.com", 389)

没有输出意味着它成功了。如果失败,它会告诉你一条红色的大错误信息。

如果这不起作用,请尝试其中一个。 AD LDAP可以在4个端口中的任何一个上运行:

  • 389:LDAP - 读取/写入单个域 - 如果您没有指定端口,则这是默认值
  • 636:LDAP over SSL - 与389相同,但已加密
  • 3268:全局编录 - 对您的AD林只读(如果您有多个域,否则它与389没有区别,除了只读)
  • 3269:SSL上的全局目录

如果其他端口之一有效,您可以在代码中指定它,如下所示:

new DirectoryEntry("LDAP://" + domainName + ":636", userName, password)

对于端口3268,您还可以使用&#34; GC://&#34;而不是指定端口:

new DirectoryEntry(&#34; GC://&#34; + domainName,userName,password)

如果这些端口都不起作用,那么您需要在继续之前计算出与您的域的网络连接。