使用活动目录API DirectoryEntry进行身份验证

时间:2016-08-19 22:12:00

标签: c# asp.net .net asp.net-mvc active-directory

我有这个方法由其他人制作,它完美无缺

问题在于,如果我为某些甚至不存在的内容更改域名,那么搜索者仍然会找到该用户名的结果,即使是错误的域名

public bool Validarcredenciales(string domain, ControlarSesiones objeto)//Metodo que valida si las credenciales son correctas.
{
    string username = objeto.Usuario;
    string pwd = objeto.Clave;
    String domainAndUsername = domain + @"\" + username;
    DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

    try
    {   //Bind to the native AdsObject to force authentication.
        //Object obj = entry.NativeObject;

        DirectorySearcher search = new DirectorySearcher(entry) { Filter = "(SAMAccountName=" + username + ")" };

        search.PropertiesToLoad.Add("cn");
        SearchResult result = search.FindOne();

        if (null == result)
        {
            MensajeError = Resources.ResourcesETB.ErrorCredenciales;
            return false;
        }

        //Update the new path to the user in the directory.
        _path = result.Path;
        FilterAttribute = (string)result.Properties["cn"][0];
    }
    catch (Exception ex)
    {
        MensajeError = Resources.ResourcesETB.ErrorCredenciales;
        return false;
    }

    return true;
}

1 个答案:

答案 0 :(得分:3)

LDAP连接使用奇怪的身份验证逻辑。如果使用" Domain \ User"创建LDAP连接。格式,并且域存在,域控制器将尝试使用指定的凭据进行连接。

但是,如果指定的域不存在,域控制器将删除域部分,并尝试使用本地域(DC的本地域)对用户进行身份验证。

在您的代码中,域名仅用于启动与域的连接(创建DirectoryEntry对象)。因此,如上所述,域控制器将删除错误的域并正确验证用户。

如果要确保用户确实在指定的域中,您可以解析用户的可分辨名称,例如LDAP://cn=user,cn=Users,dc=yourDomain,dc=com,或者解析SID以获得NTAccount } object,如in this answer所述:

DirectorySearcher search = new DirectorySearcher(entry) { Filter = "(SAMAccountName=" + username + ")" };

search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("objectsid");
SearchResult result = search.FindOne();

ResultPropertyValueCollection propertyValues = result.Properties["objectsid"];
byte[] objectsid = (byte[])propertyValues[0];

SecurityIdentifier sid = new SecurityIdentifier(sid, 0)

NTAccount account = (NTAccount) sid.Translate(typeof (NTAccount));
account.ToString(); // This gives the DOMAIN\User format for the account