VB.net - Как преобразовать SID в имя группы с Active Directory
-
27-10-2019 - |
Вопрос
Используя VB.net, как вы преобразуете SID в имя группы с Active Directory?
Пример: мне нужно получить "group_test", а не "S-1-5-32-544"
Код, который я использую,:
Public ReadOnly Property Groups As IdentityReferenceCollection
Get
Dim irc As IdentityReferenceCollection
Dim ir As IdentityReference
irc = WindowsIdentity.GetCurrent().Groups
Dim strGroupName As String
For Each ir In irc
Dim mktGroup As IdentityReference = ir.Translate(GetType(NTAccount))
MsgBox(mktGroup.Value)
Debug.WriteLine(mktGroup.Value)
strGroupName = mktGroup.Value.ToString
Next
Return irc
End Get
End Property
или что -то вроде этого?
currentUser = WindowsIdentity.GetCurrent()
For Each refGroup As IdentityReference In currentUser.Groups
Dim acc As NTAccount = TryCast(refGroup.Translate(GetType(NTAccount)), NTAccount)
If AdminGroupName = acc.Value Then
ret = "999"
End If
If UsersGroupName = acc.Value Then
ret = "1"
End If
Как бы вы адаптировали его к этому коду? (Если пользователь находится в xx Group, показать xx group in dropel down)
For Each UserGroup In WindowsIdentity.GetCurrent().Groups
If mktGroup.Value = "BIG" Then
Dim Company = ac1.Cast(Of MarketingCompany).Where(Function(ac) ac.MarketingCompanyShort = "BIG").FirstOrDefault
If Company IsNot Nothing Then
marketingCo.Items.Add(String.Format("{0} | {1}", Company.MarketingCompanyShort, Company.MarketingCompanyName))
End If
End If
Next
Решение
Вот простой способ написания в C#, я думаю, что это не сложно адаптировать:
/* Retreiving object from SID
*/
string SidLDAPURLForm = "LDAP://WM2008R2ENT:389/<SID={0}>";
System.Security.Principal.SecurityIdentifier sidToFind = new System.Security.Principal.SecurityIdentifier("S-1-5-21-3115856885-816991240-3296679909-1106");
DirectoryEntry userEntry = new DirectoryEntry(string.Format(SidLDAPURLForm, sidToFind.Value));
string name = userEntry.Properties["cn"].Value.ToString();
Вот в vb .net благодаря Отражатель
Dim SidLDAPURLForm As String = "LDAP://WM2008R2ENT:389/<SID={0}>"
Dim sidToFind As New SecurityIdentifier("S-1-5-21-3115856885-816991240-3296679909-1106")
Dim userEntry As New DirectoryEntry(String.Format(SidLDAPURLForm, sidToFind.Value))
Dim name As String = userEntry.Properties.Item("cn").Value.ToString
---- Отредактировано ----- вот то, что вы хотите, но это то же самое, что ранее дано @Biggstrc
Private Shared Sub Main(args As String())
Dim currentUser As WindowsIdentity = WindowsIdentity.GetCurrent()
For Each iRef As IdentityReference In currentUser.Groups
Console.WriteLine(iRef.Translate(GetType(NTAccount)))
Next
End Sub
Другие советы
Код в C#:
public static string GetGroupNameBySid(string sid)
{
using(var ctx =
new PrincipalContext(ContextType.Domain))
{
using(avr group =
GroupPrincipal.FindByIdentity(
ctx,
IdentityType.Sid,
sid))
{
return group?.SamAccountName;
}
}
}
Вы должны добавить System.directoryServices.accountmanagement.dll. Если у вас есть какие -либо проблемы с подключением к AD, вы можете попробовать добавить имя сервера рекламы в конструктор PrincipLOCNEXT.
Вот ссылка на то, как преобразовать SID на имя: http://vbdotnet.canbal.com/view.php?sessionId=JEF85K%2B%2BEBJ9PZ%2BWZ9HJICW%2FYEPTADXFCPYCOVZ7JS%3D
По сути, вы получите обратно объект DirectoryEntry, который затем можете использовать для получения имени. Однако, если вы ищете то, что я считаю более простым методом для этого, просто возьмите текущего пользователя и сделайте поиск в рекламе для членства в группе. Вот пример того, как это сделать (вам понадобится более крупная статья, чтобы фактически выполнить вашу задачу, но этот код является конкретным ответом на ваш вопрос): http://www.codeproject.com/kb/system/everythinginad.aspx#39
Извините за то, что код находится в C#. Тем не менее, вы должны быть в состоянии просто использовать конвертер для преобразования его в VB.NET без проблем.
Получить членство группы пользователей зарегистрированного пользователя от ASP.NET в C#
public ArrayList Groups()
{
ArrayList groups = new ArrayList();
foreach (System.Security.Principal.IdentityReference group in
System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
{
groups.Add(group.Translate(typeof
(System.Security.Principal.NTAccount)).ToString());
}
return groups;
}
Получите членство группы пользователей зарегистрированного пользователя от ASP.NET в VB.NET с помощью Инструмент преобразователя разработчика Fusion Fusion:
Public Function Groups() As ArrayList
Dim groups__1 As New ArrayList()
For Each group As System.Security.Principal.IdentityReference In System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups
groups__1.Add(group.Translate(GetType(System.Security.Principal.NTAccount)).ToString())
Next
Return groups__1
End Function