VB.NET: cómo ver si el nombre del grupo del usuario actual coincide con un nombre de grupo especificado utilizando roles de Active Directory y SID
-
28-10-2019 - |
Pregunta
Estoy tratando de hacer coincidir un nombre de grupo específico y ver si existe para el usuario iniciado actualmente utilizando los roles de Active Directory. Si el nombre del grupo existe para el usuario actual, quiero que ese nombre de grupo se muestre en una lista desplegable. Ejemplo: si el usuario actual está en un grupo grande, muestre grande en la lista desplegable.
Problema: Todo lo que estoy obteniendo es SMYS y no puedo obtener nada para que coincida con el nombre del grupo y no aparecerá nada en la lista desplegable.
También recibo el siguiente error:
Error: Object variable or WIth block variable not set.
¿¿Cómo puedo solucionar esto??
Aquí está el código que estoy usando:
Private Sub GetMarketingCompanies()
' code to populate marketing company drop down list based on the current logged in users active directory group that
' corresponds to which marketing company they are in
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
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
¡Gracias por mirar! ¡Cualquier respuesta útil será votada!
Solución 3
Terminé haciendo lo siguiente para arreglar el código:
- Eliminar el bucle for que llama a usergroup en windowsidentity.getCurrent (). grupos
- Poner todo el código en el bucle para cada bucle que llama a IdentityReference en IdentityReferenceCollection
- Agregar variable booleana McIsloaded para hacer el administrador, no administrador si las declaraciones funcionan
- Deshabilitar msgbox (mktgroup.value) ya que esto era solo para prueba y error para ver qué valores se estaban devolviendo
Aquí está el código:
Private Sub GetMarketingCompanies()
Try
Dim ac1 As Array
ac1 = proxy.GetMarketingCompanyNames("test", "test")
' code to populate marketing company drop down list based on the current logged in users active directory group that
' corresponds to which marketing company they are in
Dim irc As IdentityReferenceCollection
Dim ir As IdentityReference
irc = WindowsIdentity.GetCurrent().Groups
Dim strGroupName As String
Dim mcisloaded As Boolean
' Translate the current user's active directory groups
For Each ir In irc
Dim mktGroup As IdentityReference = ir.Translate(GetType(NTAccount))
' MsgBox(mktGroup.Value)
Debug.WriteLine(mktGroup.Value)
strGroupName = mktGroup.Value.ToString
' If the user is in the admin group, load all marketing companies
If mktGroup.Value = "ALG\ACOMP_USER_ADMIN" Then
mcisloaded = True
For Each item In ac1
marketingCo.Items.Add(String.Format("{0} | {1}", item.MarketingCompanyShort, item.MarketingCompanyName))
Next
End If
'If the user is not in the admin group, load marketing companies individually
If Not mktGroup.Value = "ALG\ACOMP_USER_ADMIN" Then
mcisloaded = False
If mcisloaded = False Then
If mktGroup.Value = "ALG\ACOMP_USER_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
If mktGroup.Value = "ALG\ACOMP_USER_AMG" Then
Dim Company = ac1.Cast(Of MarketingCompany).Where(Function(ac) ac.MarketingCompanyShort = "AMG").FirstOrDefault
If Company IsNot Nothing Then
marketingCo.Items.Add(String.Format("{0} | {1}", Company.MarketingCompanyShort, Company.MarketingCompanyName))
End If
End If
' ... Code for loading the rest of the marketing groups
End If
End If
ACTUALIZACIÓN 6-7-11: Aquí hay una versión más limpia del ciclismo a través de todos los nombres de los grupos de Active Directory utilizando un divisor de cadena para obtener las últimas 3 letras que identifican a la compañía de marketing, en lugar de una serie de declaraciones IF para cada empresa de marketing:
Private Sub GetMarketingCompanies()
Try
Dim marketingCompanyNamesArray As Array
marketingCompanyNamesArray = proxy.GetMarketingCompanyNames("test", "test")
' code to populate marketing company drop down list based on the current logged in users active directory group that
' corresponds to which marketing company they are in
Dim identityReferenceCollection As IdentityReferenceCollection
Dim identityReference As IdentityReference
identityReferenceCollection = WindowsIdentity.GetCurrent().Groups
Dim strGroupName As String
Dim mcisloaded As Boolean
' Translate the current user's active directory groups
For Each identityReference In identityReferenceCollection
Dim mktGroup As IdentityReference = identityReference.Translate(GetType(NTAccount))
' MsgBox(mktGroup.Value)
' Debug.WriteLine(mktGroup.Value)
strGroupName = mktGroup.Value.ToString
' Locally User group is ALG\ACOMP_USER_ADMIN , deployed ALGWEB\ACOMP_USER_ADMIN
' If the user is in the admin group, load all marketing companies
If mktGroup.Value = "ALG\ACOMP_USER_ADMIN" Then
mcisloaded = True
For Each item In marketingCompanyNamesArray
marketingCo.Items.Add(String.Format("{0} | {1}", item.MarketingCompanyShort, item.MarketingCompanyName))
Next
Else
'If not admin user (mcisloaded = False) load each group individually if it appears in AD
' For Each UserGroup In WindowsIdentity.GetCurrent().Groups that begins with ALG\ACOMP_USER, load marketing companies
Dim MarketingCompanyShortName As String = ""
Dim mktGroupName As String = mktGroup.Value
If mktGroupName.StartsWith("ALG\ACOMP_USER") Then
Dim marketingGroupNameParts() As String = Split(mktGroupName, "_")
'Load MarketingCompanyShortName from the end of marketingGroupNameParts - example: ACOMP_USER_BIG
MarketingCompanyShortName = marketingGroupNameParts(2)
'If MarketingCompanyShortName exists, load it into the dropdownlist
Dim Company = marketingCompanyNamesArray.Cast(Of MarketingCompany).Where(Function(ac) ac.MarketingCompanyShort = MarketingCompanyShortName).FirstOrDefault
If Company IsNot Nothing Then
marketingCo.Items.Add(String.Format("{0} | {1}", Company.MarketingCompanyShort, Company.MarketingCompanyName))
End If
End If
End If
Otros consejos
No estoy seguro de a qué se refiere los roles, pero lo siguiente enumerará los grupos de usuarios actuales (tanto locales como de dominio):
For Each ir As IdentityReference In WindowsIdentity.GetCurrent.Groups
Debug.WriteLine(CType(ir.Translate(GetType(NTAccount)), NTAccount).Value)
Next
En respuesta a su respuesta, me sorprende que si esto es lo que desea hacer lo siguiente es probablemente más eficiente y más fácil de leer:
Dim p As WindowsPrincipal = New WindowsPrincipal(WindowsIdentity.GetCurrent())
If p.IsInRole("ALG\ACOMP_USER_ADMIN") Then
'load all groups
ElseIf p.IsInRole("ALG\ACOMP_USER_BIG") Then
'load BIG groups
ElseIf p.IsInRole("ALG\ACOMP_USER_AMG") Then
'load AMG groups
'etc
End If