Foros del Web » Programación para mayores de 30 ;) » .NET »

[SOLUCIONADO] Obtener nombre, email y grupo del directorio activo

Estas en el tema de Obtener nombre, email y grupo del directorio activo en el foro de .NET en Foros del Web. Hola; Tengo una aplicación web en la que en un principio tenia una Login.aspx en la cual metía el nombre de usuario y contraseña y ...
  #1 (permalink)  
Antiguo 29/01/2013, 07:57
 
Fecha de Ingreso: abril-2012
Mensajes: 449
Antigüedad: 12 años
Puntos: 7
Exclamación Obtener nombre, email y grupo del directorio activo

Hola;
Tengo una aplicación web en la que en un principio tenia una Login.aspx en la cual metía el nombre de usuario y contraseña y si esto correspondía con los datos del directorio activo la aplicación mostraba una PaginaPrincipal.aspx.

Ahora me han dicho que tengo que quitar ese Login.aspx y mostrar directamente la PaginaPrincipal.aspx obteniendo el nombre de usuario, email y grupos de este desde el directorio activo. Es decir, si yo accedo a mi ordenador con mi usuario y contraseña que una vez que acceda a esta aplicación me coja mis datos del directorio activo.

Os dejo las funciones que tenia en Login.aspx para que me echéis una mano.

Código vb.net:
Ver original
  1. Imports System.Text
  2. Imports System.Collections
  3. Imports System.Collections.Generic
  4. Imports System.DirectoryServices
  5. Imports System.DirectoryServices.ActiveDirectory
  6. Imports System.Security
  7. Imports System.Security.Permissions
  8.  
  9. Public Class Login
  10.     Inherits System.Web.UI.Page
  11.  
  12.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  13.         'RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString("ReturnUrl"))
  14.     End Sub
  15.  
  16.     Protected Sub LoginButton_Click(sender As Object, e As EventArgs) Handles LoginButton.Click
  17.         'Dim usuario As String
  18.         'Dim pass As String
  19.         Dim valido, valido2 As Boolean
  20.         Dim nombre, email, grupo As String
  21.  
  22.         'usuario = Me.UserName.Text
  23.         'pass = Me.Password.Text
  24.  
  25.         If Me.UserName.Text = "" Or Me.Password.Text = "" Then
  26.  
  27.             errorLabel.Text = "*Introduzca los datos de acceso necesarios"
  28.         Else
  29.             GetDirectoryEntry(Me.UserName.Text, Me.Password.Text)
  30.             valido = IsValidADLogin(Me.UserName.Text, Me.Password.Text)
  31.  
  32.             If valido Then
  33.  
  34.                 valido2 = ValidateUser(Me.UserName.Text, Me.Password.Text)
  35.  
  36.                 If valido2 Then
  37.                     Dim valoresarray As String()
  38.  
  39.                     valoresarray = FullName(Me.UserName.Text, Me.Password.Text)
  40.                     nombre = valoresarray(0)
  41.                     email = valoresarray(1)
  42.                     grupo = obtenergrupo(Me.UserName.Text, Me.Password.Text)
  43.                     'grupo = 2
  44.                     Session.Add("nombre", nombre)
  45.                     Session.Add("email", email)
  46.                     Session.Add("grupoUsuario", grupo)
  47.                     'Response.Redirect(String.Format("~/PaginaPrincipal.aspx?nombre={0}", nombre))
  48.                     Response.Redirect(String.Format("~/PaginaPrincipal.aspx"))
  49.                     'MsgBox(nombre)
  50.                 Else
  51.  
  52.                     Me.UserName.Text = ""
  53.                     Me.Password.Text = ""
  54.                     errorLabel.Text = "*Datos incorrectos. Vuelva a introducir los datos de acceso."
  55.                 End If
  56.             Else
  57.                 Me.UserName.Text = ""
  58.                 Me.Password.Text = ""
  59.                 errorLabel.Text = "*Datos incorrectos. Vuelva a introducir los datos de acceso."
  60.             End If
  61.         End If
  62.     End Sub
  63.  
  64.     Public Shared Function GetDirectoryEntry(ByVal usuario As String, ByVal pass As String) As DirectoryEntry
  65.         'Of course change the information for the LDAP to your network
  66.         Dim dirEntry As New DirectoryEntry
  67.  
  68.         dirEntry.Path = ("LDAP://192.168.1.108/DC=indar,DC=local")
  69.         dirEntry.AuthenticationType = AuthenticationTypes.Secure
  70.         dirEntry.Username = "indar.local\" + usuario
  71.         dirEntry.Password = pass
  72.  
  73.         Return dirEntry
  74.     End Function
  75.  
  76.     Public Shared Function ExtractUserName(ByVal path As String) As String
  77.         'Split on the "\"
  78.         Dim userPath As String() = path.Split(New Char() {"\"c})
  79.  
  80.         'Return the rest (username part)
  81.         Return userPath((userPath.Length - 1))
  82.     End Function
  83.  
  84.     Public Function IsValidADLogin(ByVal user As String, ByVal pass As String) As Boolean
  85.        
  86.         Try
  87.             'Create a DirectorySearcher Object (used for searching the AD)
  88.             Dim search As New DirectorySearcher()
  89.  
  90.             'Set the filter on the searcher object to look for the SAMAccountName, givenName and the sn (Sur Name)
  91.             search.Filter = "(sAMAccountName=" + user + ")"
  92.  
  93.             'Use the .FindOne() Method to stop as soon as a match is found
  94.             Dim result As SearchResult = search.FindOne()
  95.  
  96.             'Now check to see if a result was found
  97.             If result Is Nothing Then
  98.  
  99.                 'Login isn't valid
  100.                 Return False
  101.             Else
  102.  
  103.                 'Valid login
  104.                 Return True
  105.             End If
  106.         Catch ex As Exception
  107.             MsgBox("Active Directory Error" & Chr(13) & Chr(13) & ex.Message)
  108.         End Try
  109.     End Function
  110.  
  111.     Public Function ValidateUser(ByVal user As String, ByVal pass As String) As Boolean
  112.         Dim adsEntry As New DirectoryEntry("LDAP://192.168.1.108/DC=indar,DC=local", User, pass)
  113.         Dim adsSearcher As New DirectorySearcher(adsEntry)
  114.  
  115.         adsSearcher.Filter = "(sAMAccountName=" + user + ")"
  116.         Dim bSucceded As Boolean = False
  117.  
  118.         Try
  119.             Dim adsSearchResult As SearchResult
  120.  
  121.             adsSearchResult = adsSearcher.FindOne()
  122.             bSucceded = True
  123.             adsEntry.Close()
  124.         Catch ex As Exception
  125.  
  126.             adsEntry.Close()
  127.         End Try
  128.         Return bSucceded
  129.     End Function
  130.  
  131.     Public Function FullName(ByVal user As String, ByVal pass As String) As String()
  132.         Dim adsEntry As New DirectoryEntry("LDAP://192.168.1.108/DC=indar,DC=local", user, pass)
  133.         Dim deSearch As New DirectorySearcher(adsEntry)
  134.         Dim properties() As String = {"fullname"}
  135.         deSearch.SearchScope = SearchScope.Subtree
  136.         deSearch.ReferralChasing = ReferralChasingOption.All
  137.         deSearch.PropertiesToLoad.AddRange(properties)
  138.         deSearch.Filter = "(sAMAccountName=" + user + ")"
  139.  
  140.         Dim result As SearchResult
  141.         result = deSearch.FindOne()
  142.         Dim directoryEntry As New DirectoryEntry
  143.         directoryEntry = result.GetDirectoryEntry()
  144.         Dim displayname, mail As String
  145.         displayname = directoryEntry.Properties("displayname").Value
  146.         mail = directoryEntry.Properties("mail").Value
  147.         Dim ar As String() = {displayname, mail}
  148.         Return ar
  149.     End Function
  150.  
  151.     Private Function obtenergrupo(ByVal user As String, ByVal pass As String)
  152.         Dim deGlobal As New DirectoryEntry("LDAP://192.168.1.108/DC=indar,DC=local", user, pass)
  153.         Dim ds As DirectorySearcher = New DirectorySearcher(deGlobal)
  154.  
  155.         ds.SearchScope = DirectoryServices.SearchScope.Subtree
  156.         ds.Filter = "(&(objectcategory=user)(SAMAccountName=" & user & "))"
  157.         Dim res As SearchResult = ds.FindOne
  158.         Dim grupo As String
  159.         Dim grupo1, grupo2, grupo3 As Integer
  160.         For i = 0 To res.Properties("memberOf").Count() - 1
  161.             grupo = res.Properties("memberOf")(i).ToString
  162.  
  163.             If grupo = "CN=GHDGAprobacion,OU=UOHDG,OU=UOAplicaciones,DC=indar,DC=local" Then
  164.                 grupo1 = 1
  165.             ElseIf grupo = "CN=GHDGVisas,OU=UOHDG,OU=UOAplicaciones,DC=indar,DC=local" Then
  166.                 grupo2 = 2
  167.             Else
  168.                 grupo3 = 3
  169.             End If
  170.         Next
  171.  
  172.         If grupo1 = 1 Then
  173.  
  174.             If grupo1 = 1 And grupo2 = 2 And grupo3 = 3 Then
  175.  
  176.                 Return grupo1
  177.             End If
  178.  
  179.             Return grupo1
  180.         End If
  181.  
  182.         If grupo2 = 2 Then
  183.             If grupo2 = 2 And grupo3 = 3 Then
  184.  
  185.                 Return grupo2
  186.             End If
  187.  
  188.             Return grupo2
  189.         End If
  190.  
  191.         If grupo3 = 3 Then
  192.  
  193.             Return grupo3
  194.         End If
  195.     End Function
  196. End Class
__________________
Gracias por todo;

Un saludo
  #2 (permalink)  
Antiguo 29/01/2013, 09:34
 
Fecha de Ingreso: abril-2012
Mensajes: 449
Antigüedad: 12 años
Puntos: 7
Pregunta Respuesta: Obtener nombre, email y grupo del directorio activo

[QUOTE=maialenlopez;4357822]Hola;
Tengo una aplicación web en la que en un principio tenia una Login.aspx en la cual metía el nombre de usuario y contraseña y si esto correspondía con los datos del directorio activo la aplicación mostraba una PaginaPrincipal.aspx.

Ahora me han dicho que tengo que quitar ese Login.aspx y mostrar directamente la PaginaPrincipal.aspx obteniendo el nombre de usuario, email y grupos de este desde el directorio activo. Es decir, si yo accedo a mi ordenador con mi usuario y contraseña que una vez que acceda a esta aplicación me coja mis datos del directorio activo.

Os dejo las funciones que tenia en Login.aspx para que me echéis una mano.

He conseguido hacerlo mediante esto y utilizando las funciones que tenia echas en Login.aspx
Código vb.net:
Ver original
  1. Imports System.Text
  2. Imports System.Collections
  3. Imports System.Collections.Generic
  4. Imports System.DirectoryServices
  5. Imports System.DirectoryServices.ActiveDirectory
  6. Imports System.Security
  7. Imports System.Security.Permissions
  8.  
  9. Public Class _Default
  10.     Inherits System.Web.UI.Page
  11.  
  12.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  13.         Dim username, userpass, user, pass, nombre, email, grupo As String
  14.         Dim contar, i As Integer
  15.         Dim valoresarray As String()
  16.  
  17.         If IsPostBack = False Then
  18.  
  19.             username = HttpContext.Current.Request.ServerVariables("AUTH_USER")
  20.             contar = username.Length
  21.             i = username.IndexOf("\")
  22.             user = username.Substring(i + 1)
  23.             valoresarray = FullName(user)
  24.             nombre = valoresarray(0)
  25.             email = valoresarray(1)
  26.             grupo = obtenergrupo(user)
  27.  
  28.             Session.Add("nombre", nombre)
  29.             Session.Add("email", email)
  30.             Session.Add("grupoUsuario", grupo)
  31.  
  32.             Me.nombreUsuario.Text = CType(Session("nombre"), String)
  33.             Me.emailUsuario.Text = CType(Session("email"), String)
  34.         End If
  35.     End Sub
  36.  
  37.     Public Function FullName(ByVal user As String) As String()
  38.         Dim adsEntry As New DirectoryEntry("LDAP://192.168.1.108/DC=indar,DC=local")
  39.         Dim deSearch As New DirectorySearcher(adsEntry)
  40.         Dim properties() As String = {"fullname"}
  41.         deSearch.SearchScope = SearchScope.Subtree
  42.         deSearch.ReferralChasing = ReferralChasingOption.All
  43.         deSearch.PropertiesToLoad.AddRange(properties)
  44.         deSearch.Filter = "(sAMAccountName=" + user + ")"
  45.  
  46.         Dim result As SearchResult
  47.         result = deSearch.FindOne()
  48.         Dim directoryEntry As New DirectoryEntry
  49.         directoryEntry = result.GetDirectoryEntry()
  50.         Dim displayname, mail As String
  51.         displayname = directoryEntry.Properties("displayname").Value
  52.         mail = directoryEntry.Properties("mail").Value
  53.         Dim ar As String() = {displayname, mail}
  54.         Return ar
  55.     End Function
  56.  
  57.     Private Function obtenergrupo(ByVal user As String)
  58.         Dim deGlobal As New DirectoryEntry("LDAP://192.168.1.108/DC=indar,DC=local")
  59.         Dim ds As DirectorySearcher = New DirectorySearcher(deGlobal)
  60.  
  61.         ds.SearchScope = DirectoryServices.SearchScope.Subtree
  62.         ds.Filter = "(&(objectcategory=user)(SAMAccountName=" & user & "))"
  63.         Dim res As SearchResult = ds.FindOne
  64.         Dim grupo As String
  65.         Dim grupo1, grupo2, grupo3 As Integer
  66.         For i = 0 To res.Properties("memberOf").Count() - 1
  67.             grupo = res.Properties("memberOf")(i).ToString
  68.  
  69.             If grupo = "CN=GHDGAprobacion,OU=UOHDG,OU=UOAplicaciones,DC=indar,DC=local" Then
  70.                 grupo1 = 1
  71.             ElseIf grupo = "CN=GHDGVisas,OU=UOHDG,OU=UOAplicaciones,DC=indar,DC=local" Then
  72.                 grupo2 = 2
  73.             Else
  74.                 grupo3 = 3
  75.             End If
  76.         Next
  77.  
  78.         If grupo1 = 1 Then
  79.  
  80.             If grupo1 = 1 And grupo2 = 2 And grupo3 = 3 Then
  81.  
  82.                 Return grupo1
  83.             End If
  84.  
  85.             Return grupo1
  86.         End If
  87.  
  88.         If grupo2 = 2 Then
  89.             If grupo2 = 2 And grupo3 = 3 Then
  90.  
  91.                 Return grupo2
  92.             End If
  93.  
  94.             Return grupo2
  95.         End If
  96.  
  97.         If grupo3 = 3 Then
  98.  
  99.             Return grupo3
  100.         End If
  101.     End Function
  102.  
  103. End Class

Pero tengo un problema haber si me podéis ayudar. Esto si lo hago localmente funciona perfecto pero el problema es que esta aplicación tiene que estar en un servidor y no cuando cojo el usuario mediante username = HttpContext.Current.Request.ServerVariables("AUTH_ USER") me coge el nombre del servidor y lo que quiero es que coja el nombre del usuario en el que se está ejecutando la aplicacion.

Me podéis echar una mano?
__________________
Gracias por todo;

Un saludo

Etiquetas: activo, aplicaciones, directorio, email, grupo, net, nombre
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 15:28.