简体   繁体   English

asp.net Web API的LDAP身份验证

[英]LDAP Authentication for asp.net Web API

I'm working on WEB API project using ASP.NET technology. 我正在使用ASP.NET技术进行WEB API项目。 This Web API need to check the user from AD Active Directory, as domain authentication using LDEP:// 该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;
    }

so I call this method with ajax for test only 所以我只用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); }
    });
});

Unfortunately, I always receiving bad request or this below error 不幸的是,我总是收到错误的请求或以下错误

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

Can you please provide me with a guide how to resolve this issue, as I have never work with security programming before. 您是否可以向我提供如何解决此问题的指南,因为我以前从未使用过安全编程。

The error is down to your application failing to bind to the LDAP server. 该错误归因于您的应用程序无法绑定到LDAP服务器。 Firstly, I would recommend adding a target LDAP server to your query string and then formatting the query string correctly to represent the domain DN= as well as any specific Organisation Units OU= etc... 首先,我建议将目标LDAP服务器添加到您的查询字符串中,然后正确设置查询字符串的格式以表示域DN=以及任何特定的组织单位OU=等。

The query string would look something like this: 查询字符串如下所示:

LDAP://contoso.local/DC=contoso,DC=local

I've created an example below which performs the request using a GET (Not recommended for obvious reasons) along with a helper method to convert the domain into a friendly LDAP string. 我在下面创建了一个示例,该示例使用GET (出于明显的原因不建议使用)执行请求,并使用辅助方法将域转换为友好的LDAP字符串。 The response outputs the result properties into JSON so you can manipulate how you see fit. 响应将结果属性输出到JSON中,因此您可以控制自己认为合适的方式。

   public JsonResult CheckAdCreds(string server, string domain, string username, string password)
    {
        try
        {
            var ldapDomainString = LdapStringFromDomain(domain, server);

            using (var entry = new DirectoryEntry(ldapDomainString, username, password))
            {
                using (var search = new DirectorySearcher(entry))
                {
                    search.Filter = $"(&(objectClass=user)(objectCategory=user) (sAMAccountName={username}))";
                    var result = search.FindOne();
                    return Json(result.Properties, JsonRequestBehavior.AllowGet);
                }
            }
        }
        catch (Exception ex)
        {
            return Json(new { Error = ex.Message }, JsonRequestBehavior.AllowGet);
        }
    }

Helper method which converts the domain string into an LDAP friendly string: 将域字符串转换为LDAP友好字符串的Helper方法:

    private string LdapStringFromDomain(string domain, string server)
    {
        var ldapString = $"LDAP://{server}/";
        var domainArr = domain.Split('.');

        for (int i = 0; i < domainArr.Length; i++)
        {
            ldapString += $"DC={domainArr[i]}";

            if (i != domainArr.Length - 1)
                ldapString += ",";
        }
        return ldapString;
    }

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM