LDAP Authentication for asp.net Web API

2

I'm working on WEB API project using ASP.NET technology. This Web API need to check the user from AD Active Directory, as domain authentication using 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

$(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.

asp.net
authentication
ldap
asp.net-web-api2

1 Answer

0

The error is down to your application failing to bind to the LDAP server. 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...

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. The response outputs the result properties into JSON so you can manipulate how you see fit.

   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:

    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.

answered on Stack Overflow May 24, 2018 by Kitson88 • edited May 24, 2018 by Kitson88

User contributions licensed under CC BY-SA 3.0