Pregunta

Usando VB.NET, ¿cómo se convierte el SID en el nombre del grupo con Active Directory?

Ejemplo: necesito obtener "group_test" y no "S-1-5-32-544"

El código que estoy usando es:

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

¿o algo como esto?

        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

¿Cómo lo adaptarías a este código? (Si el usuario está en el grupo XX, muestra el grupo XX en la lista desplegable)

        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
¿Fue útil?

Solución

Aquí hay una forma simple escrita en C#, creo que no es difícil de adaptar:

  /* 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();

Aquí está en VB .net gracias a REFLECTOR

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

---- Editado ----- Entonces esto es lo que quieres, pero es lo mismo que anteriormente fue dado por @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

Otros consejos

Código en 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;
            }
        }
    }

Debe agregar ensamblaje System.DirectoryServices.AccountManagement.dll. Si tiene algún problema con la conexión a AD, puede intentar agregar el nombre del servidor de anuncios en el constructor de principios.

Aquí hay un enlace sobre cómo convertir un SID a un nombre: http://vbdotnet.canbal.com/view.php?sessionID=Jef85K%2B%2BebJ9pz%2BWZ9HJJICW%2FYEPTADXFCPYCOVZ7JS%3D

Básicamente, obtienes un objeto DirectoryEntry que luego puedes usar para obtener el nombre. Sin embargo, si está buscando lo que creo que es un método más fácil para hacer esto, simplemente tome al usuario actual y busque en anuncios para las membresías de su grupo. Aquí hay un ejemplo de cómo hacerlo (necesitará el artículo más grande para realizar su tarea, pero este código es la respuesta específica a su pregunta): http://www.codeproject.com/kb/system/everythinginad.aspx#39

Perdón por el hecho de que el código está en C#. Sin embargo, debería poder usar un convertidor para convertirlo en VB.NET sin ningún problema.

Obtenga membresías del grupo de usuarios del usuario iniciado en ASP.NET en 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;
 }

Obtenga membresías del grupo de usuarios del usuario iniciado en ASP.NET en VB.NET usando Herramienta convertidor de desarrollador 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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top