天天看點

dotNET Core 中怎樣操作AD(續1)

在之前的文章《dotNET Core 中怎樣操作 AD?》中主要以将AD的資料同步到資料庫的場景來描述了在 dotNetCore 中怎樣操作AD,本文将繼續介紹一些在 dotNetCore 中操作 AD 的其他常用操作。

環境

  • dotNET Core:3.0
  • Novell.Directory.Ldap.NETStandard2_0:3.1.0
  • AD:windows server 2012

基本操作

查詢

在 AD 中進行使用者的操作,通常需要先判斷使用者是否存在,這時就需要使用查詢了,用下面代碼可以進行 AD 中的查詢:

var entities = _connection.Search(ADClient.BaseDC, 		LdapConnection.SCOPE_SUB,
     $"sAMAccountName={loginName}",
     null, false);
           

參數說明:

  • base: 指定的總體搜尋範圍,通常在建立連接配接時會指定一個 BaseDC,表示後面的操作在此 DC 範圍内,如果希望從根開始搜尋,此參數可傳空
  • scope:查詢周遊的方式,分為 SCOPE_BASE 、SCOPE_ONE 和 SCOPE_SUB 三種
    • SCOPE_BASE:通常知道對象的 DN,并希望擷取其屬性時,使用此項
    • SCOPE_ONE:查詢 base 的下一層級
    • SCOPE_SUB:查詢 base 下的所有對象,包含 base
  • filter:用來過濾的表達式,下面列出一些常用的表達式
(cn=oec2003):傳回 cn 等于 oec2003 的使用者
(sAMAccountName=oec*):傳回登入名以 oec 開頭的使用者
!(cn=oec2003):傳回 cn 不等于 oec2003 的使用者
(|(cn=oec2003)(telephonenumber=888*)):傳回 cn 等于 oec2003 ,或者電話号碼以 888 開頭的使用者
(&(cn=oec2003)(telephonenumber=888*)):傳回 cn 等于 oec2003 ,并且電話号碼以 888 開頭的使用者
           

其他更多的表達式可以參考官方文檔:https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/bovtuda.html

  • attrs:字元串數組,可以指定傳回的屬性的清單,不指定傳回所有的屬性

例如根據登入名來查詢使用者的示例代碼如下:

public static LdapEntry GetUser(string loginName)
{
    var entities = _connection.Search(ADClient.BaseDC,LdapConnection.SCOPE_SUB,
               $"sAMAccountName={loginName}",
               null, false);
    LdapEntry entry = null;
    while (entities.HasMore())
    {

        try
        {
            entry = entities.Next();
        }
        catch (LdapException e)
        {
            Console.WriteLine($"GetUser Error: {e.Message}");
            continue;
        }
    }

    return entry;
}
           

添加使用者

public static bool AddUser(string userName, string loginName, string defaultPwd, string container)
{
    //設定預設密碼
    defaultPwd = $"\"{defaultPwd}\"";
    sbyte[] encodedBytes = SupportClass.ToSByteArray(Encoding.Unicode.GetBytes(defaultPwd));

    LdapAttributeSet attributeSet = new LdapAttributeSet();
    attributeSet.Add(new LdapAttribute("objectclass", "user"));
    attributeSet.Add(new LdapAttribute("sAMAccountName", userName));
    //設定建立使用者後啟用
    attributeSet.Add(new LdapAttribute("userAccountControl", (66080).ToString()));
    attributeSet.Add(new LdapAttribute("unicodePwd", encodedBytes));

    string dn = $"CN={loginName},{container}";
    LdapEntry newEntry = new LdapEntry(dn, attributeSet);
    _connection.Add(newEntry);
    return true;
}
           

注意點:

  • 預設密碼的設定需要給密碼加上引号
  • 預設情況下建立的使用者是禁用的,如果要啟用需要加上代碼

    attributeSet.Add(new LdapAttribute("userAccountControl", (66080).ToString()));

修改密碼

public static bool UpdatePassword(string loginName, string password)
{
    LdapEntry entry = GetUser(loginName);
    if (entry == null)
    {
        throw new Exception($"名為:{loginName} 的使用者在AD中不存在");
    }

    password = $"\"{password}\"";
    sbyte[] encodedBytes = SupportClass.ToSByteArray(Encoding.Unicode.GetBytes(password));
    LdapAttribute attributePassword = new LdapAttribute("unicodePwd", encodedBytes);

    _connection.Modify(entry.DN, new LdapModification(LdapModification.REPLACE, attributePassword));

    return true;
}
           

禁用使用者

public static bool EnblaedUser(string loginName)
{
    LdapEntry entry = GetUser(loginName);
    if (entry == null)
    {
        throw new Exception($"名為:{loginName} 的使用者在AD中不存在");
    }

    LdapAttribute attributePassword = new LdapAttribute("userAccountControl", (66082).ToString());
    _connection.Modify(entry.DN, new LdapModification(LdapModification.REPLACE, attributePassword));

    return true;
}
           

啟用使用者

public static bool EnblaedUser(string loginName)
{
    LdapEntry entry = GetUser(loginName);
    if (entry == null)
    {
        throw new Exception($"名為:{loginName} 的使用者在AD中不存在");
    }

    LdapAttribute attributePassword = new LdapAttribute("userAccountControl", (66080).ToString());
    _connection.Modify(entry.DN, new LdapModification(LdapModification.REPLACE, attributePassword));

    return true;
}
           

移動使用者到新的 OU

public static bool MoveUserToOU(string loginName, string rcn = "", string ouContainer = "")
{
    LdapEntry entry = GetUser(loginName);
    if (entry == null)
    {
        throw new Exception($"名為:{loginName} 的使用者在AD中不存在");
    }

    string cn = entry.AttrStringValue("cn");
    cn = rcn == "" ? cn : rcn;
    string newRCN = $"CN={cn}";

    if (string.IsNullOrWhiteSpace(ouContainer))
    {
        _connection.Rename(entry.DN, newRCN, true);
    }
    else
    {
        _connection.Rename(entry.DN, newRCN, ouContainer, true);
    }

    return true;
}
           
  • 一個使用者一旦建立,DN是不能修改的,可以通過

    Rename

    方法來修改CN來達到修改DB的目的
  • 如果傳入第三個參數

    ouContainer

    ,就可以實作将使用者移動到目标OU

添加使用者到組

public static bool AddUserToGroup(string loginName, string groupDN)
{
    LdapEntry entry = GetUser(loginName);
    if (entry == null)
    {
        throw new Exception($"名為:{loginName} 的使用者在AD中不存在");
    }

    List<string> memberOf = entry.AttrStringValueArray("memberOf");
    if (memberOf.Contains(groupDN))
    {
        throw new Exception($"名為:{loginName} 的使用者已經加入了組: {groupDN}");
    }

    LdapModification[] modGroup = new LdapModification[1];
    LdapAttribute member = new LdapAttribute("member", entry.DN);
    modGroup[0] = new LdapModification(LdapModification.ADD, member);

    try
    {
        _connection.Modify(groupDN, modGroup);
    }
    catch (LdapException e)
    {
        System.Console.Error.WriteLine("Failed to modify group's attributes: " + e.LdapErrorMessage);
        return false;
    }
    catch (Exception e)
    {
        Console.Error.WriteLine("AddUserToGroup Error:" + e.Message);
        return false;
    }
    return true;
}
           

使用者從組中移除

public static bool RemoveUserFromGroup(string loginName, string groupDN)
{
    LdapEntry entry = GetUser(loginName);
    if (entry == null)
    {
        throw new Exception($"名為:{loginName} 的使用者在AD中不存在");
    }

    List<string> memberOf = entry.AttrStringValueArray("memberOf");
    if (!memberOf.Contains(groupDN))
    {
        throw new Exception($"名為:{loginName} 的使用者不存在于組: {groupDN} 中");
    }

    LdapModification[] modGroup = new LdapModification[1];
    LdapAttribute member = new LdapAttribute("member", entry.DN);
    modGroup[0] = new LdapModification(LdapModification.DELETE, member);

    try
    {
        _connection.Modify(groupDN, modGroup);
    }
    catch (LdapException e)
    {
        System.Console.Error.WriteLine("Failed to delete group's attributes: " + e.LdapErrorMessage);
        return false;
    }
    catch (Exception e)
    {
        Console.Error.WriteLine("RemoveUserFromGroup Error:" + e.Message);
        return false;
    }
    return true;
}
           

添加使用者登入到

public static bool UpdateUserWorkStation(string loginName, string computerName, UserWorkStationOperType type)
{
    LdapEntry entry = GetUser(loginName);
    if (entry == null)
    {
        throw new Exception($"名為:{loginName} 的使用者在AD中不存在");
    }

    List<string> stations = entry.AttrStringValue("userWorkstations").Split(',').ToList();
    if (type == UserWorkStationOperType.Add && !stations.Contains(computerName))
    {
        stations.Add(computerName);
    }
    else if (type == UserWorkStationOperType.Remove && stations.Contains(computerName))
    {
        stations.Remove(computerName);
    }

    LdapAttribute attributePassword = new LdapAttribute("userWorkstations", string.Join(',', stations));
    _connection.Modify(entry.DN, new LdapModification(LdapModification.REPLACE, attributePassword));
    return true;
}
           

最後

本文的示例代碼已推送到 GitHub:https://github.com/oec2003/DotNetCoreAdDemo

官網也有些示例,但不是很完善,而且有很多代碼并不能正常執行,是以才有了本示例,也會不斷完善。

希望本文對您有所幫助。

dotNET Core 中怎樣操作AD(續1)

微信公衆号:不止dotNET

作者: oec2003

出處: http://oec2003.cnblogs.com/

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連結,否則 保留追究法律責任的權利。

繼續閱讀