簡體   English   中英

使用活動目錄API DirectoryEntry進行身份驗證

[英]Authentication with active directory API DirectoryEntry

我有這個方法由別人制作,它工作得非常好

問題是,如果我為不存在的東西更改域名,搜索者仍然會找到該用戶名的結果,即使是錯誤的域名

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

LDAP連接使用奇怪的身份驗證邏輯。 如果使用“域\\用戶”格式創建LDAP連接,並且域存在,則域控制器將嘗試使用指定的憑據進行連接。

但是,如果指定的域不存在,域控制器將刪除域部分,並嘗試使用本地域(本地為DC)對用戶進行身份驗證。

在您的代碼中,域名僅用於啟動與域的連接(創建DirectoryEntry對象)。 因此,如上所述,域控制器將刪除錯誤的域並正確地驗證用戶。

如果要確保用戶確實在指定的域中,您可以解析用戶的可分辨名稱,例如LDAP://cn=user,cn=Users,dc=yourDomain,dc=com ,或解析SID以獲取NTAccount對象,如本答案中所述

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM