VB.NET - How to Convert SID to Group Name with Active Directory

12,355

Solution 1

Here is a simple way writen in C#, I think it's not to hard to adapt :

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

Here it is in VB .NET thanks to 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

---- EDITED ----- So here is what you wants, but it's the same as that was previously given by @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

Solution 2

Code in C#:

    public static string GetGroupNameBySid(string sid)
    {
        using(var ctx = 
            new PrincipalContext(ContextType.Domain))
        {
            using(var group = 
                GroupPrincipal.FindByIdentity(
                    ctx, 
                    IdentityType.Sid, 
                    sid))
            {
                return group.SamAccountName;
            }
        }
    }

You must add assembly System.DirectoryServices.AccountManagement.dll. If you have any troubles with connection to AD, you can try adding AD server name in PrincipalContext constructor.

Solution 3

Here is a link for how to convert a SID to a name: http://vbdotnet.canbal.com/view.php?sessionid=JEf85K%2B%2BeBj9Pz%2BWz9hJJicW%2FYEPtADXfcpYCovZ7js%3D

Basically, you get a DirectoryEntry object back which you can then use to get the name. However, if you are looking for what I believe to be an easier method to do this, just take the current user and do a lookup in AD for their group memberships. Here is an example of how to do that (you will need the larger article to actually accomplish your task but this code is the specific answer to your question): http://www.codeproject.com/KB/system/everythingInAD.aspx#39

Sorry about the fact that the code is in C#. However, you should be able to just use a converter to convert it to VB.NET without a problem.

Get User Group Memberships of the Logged in User from ASP.NET in 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;
 }

Get User Group Memberships of the Logged in User from ASP.NET in VB.NET using Developer Fusion's Converter Tool:

    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
Share:
12,355
Brian McCarthy
Author by

Brian McCarthy

Noob .NET Developer and UF Gator Graduate from sunny Tampa, FL using C# &amp; VB w/ Visual Studio 2017 Premium. I also do Search Engine Optimization Consulting and Wordpress configurations. Feel free to contact me on: LinkedIn, Google +, or Facebook :) Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?" -Brian Kernighan from "Elements of Programming Style

Updated on July 13, 2022

Comments

  • Brian McCarthy
    Brian McCarthy almost 2 years

    Using VB.NET, How do you Convert the sid to Group Name with Active Directory?

    example: I need to get "group_test" and not "S-1-5-32-544"

    The code I'm using is:

    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
    

    or something like this?

            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
    

    how would u adapt it to this code? (if user is in xx group, show xx group on drop down list)

            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
    
  • Brian McCarthy
    Brian McCarthy about 13 years
    @JPBlanc, thanks for your response. Can you explain what this code does? Would i need to hard code this for every SID separately?
  • JPBlanc
    JPBlanc about 13 years
    Sorry, I don't understand your question. this code translate an SID to a group name, based on Active-Directory. You just have to build a method with a string as argument on the top of it.
  • Brian McCarthy
    Brian McCarthy about 13 years
    @JPBlanc, where are you getting the value "S-1-5-21-3115856885-816991240-3296679909-1106"?
  • JPBlanc
    JPBlanc about 13 years
    I got it from a group of my Active-Directory. Your question is "How to Convert SID to Group Name with Active Directory" ? So I took a SID from my AD and give you the code to convert it to a group name.
  • Brian McCarthy
    Brian McCarthy about 13 years
    Perhaps, I'm asking the wrong question. I'm looking to match up a specific group name and see if it exists for the current logged in user but all i get is sids. let me post a new question. check the code added to the question above.
  • Brian McCarthy
    Brian McCarthy almost 13 years
    thanks for your response! Do you mean that I should add "Imports System.DirectoryServices.AccountManagement" to Default.aspx.vb? Where do I declare the PrincipalContext constructor? I'm looking on MSDN at msdn.microsoft.com/en-us/library/…, msdn.microsoft.com/en-us/library/…, and the following methods: GetGroups, GetGroups(PrincipalContext), IsMemberOf(PrincipalContext, IdentityType, String), IsMemberOf(GroupPrincipal).
  • meir
    meir almost 13 years
    @brian-mccarthy Right click on References of your project, then "Add Reference...". In .NET tab find "System.DirectoryServices.AccountManagement" component and double click it or press OK. You do not need to declare PrincipalContext constructor as this class is already defined in assembly added above. I use one argument constructor in example. If you have troubles with connection to AD (I did not have, but maybe it can occur if your AD client (i.e. your application) is not in domain), you can use two arguments constructor of PrincipalContext and pass AD server host name as the second argument.
  • Vlad
    Vlad over 8 years
    Briliantly! Just what I looked for
  • iliketurtles
    iliketurtles almost 5 years
    This is the way to do it. The Translate method returns pre-Windows 2000 names!
  • iliketurtles
    iliketurtles almost 5 years
    The Translate returns the pre-Windows 2000 name of a AD group, which can be different!