【问题标题】:LDAP Authentication for asp.net Web APIasp.net Web API 的 LDAP 身份验证
【发布时间】:2018-11-03 08:16:12
【问题描述】:

我正在使用 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.

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

【问题讨论】:

  • 不能用PrincpalContext吗?例如。 using (var context = new PrincipalContext(ContextType.Domain, domain)) { var user = UserPrincipal.FindByIdentity(context, userName); }

标签: asp.net authentication ldap asp.net-web-api2


【解决方案1】:

错误归结为您的应用程序未能绑定到 LDAP 服务器。首先,我建议将目标 LDAP 服务器添加到您的查询字符串中,然后正确格式化查询字符串以表示域 DN= 以及任何特定的组织单位 OU= 等...

查询字符串如下所示:

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

我在下面创建了一个示例,它使用GET(由于明显的原因不推荐)以及将域转换为友好 LDAP 字符串的辅助方法来执行请求。响应将结果属性输出到 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);
        }
    }

将域字符串转换为 LDAP 友好字符串的辅助方法:

    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;
    }

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2012-06-16
    • 2017-10-22
    • 1970-01-01
    • 2015-09-17
    • 2017-07-30
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多