locked
How to: Login authentcation via Active directory RRS feed

  • Question

  • User-1332707980 posted

    Hello All,
      I am new to .NET development. i have installed VS.NET 2003. We are doing a project in that ther is a Login module where the users needs to be authenitcated. We are planning to use the users NT Login ID as the login to this asp page. This server will be hosted in the intranet of our office.

    First I would like to know if it would be possible to authenticate a user via ActiveDirectory. The user basically will be logging in the page like he would in the windows (username,pwd and domain).
    Also the site will be hosted in india (i our office) and users from other countries like Germany, JApan also would login to this. All these offices are inter connected via a corporate network. So i thnk i would be able to authenticate users from a different domain also.

    Can any one give me a sample on how this works? Or is there any better solution for this

    I am using .NET 2003 (ASP.NET 1.1)

    thanks in advance

    Karthik K

    Wednesday, February 8, 2006 8:31 PM

All replies

  • User387614326 posted

    so

     

    <%@ Page Language="VB" %>
    <%@ Import Namespace = System.Security %>
    <%@ Import Namespace = System.DirectoryServices %>
    <%@ Import Namespace = system.Web %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">

        Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        End Sub

        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Try
                Dim Usuario As New DirectoryEntry
                If TextBox1.Text = "" Then
                    Label3.Text = "Ingrese User"
                ElseIf TextBox2.Text = "" Then
                    Label3.Text = "Ingrese Password"
                Else
                    Dim username As String
                    Dim valor As String
                    username = TextBox1.Text
                    Dim fullPath As String = "LDAP://dc=atrame,dc=deloitte,dc=com"
                    Usuario = New DirectoryEntry(fullPath)
                    Usuario.Username = username
                    Usuario.Password = TextBox2.Text
                    Usuario.RefreshCache()
                    valor = True 'User.Identity.IsAuthenticated
                   
                    'TextBox1.Text = ""
                    If valor = True Then
                        '  Session("email") = GetUserInfo(Usuario.Username, "mail")
                        Session("cargo") = GetUserInfo(Usuario.Username, "title")
                        Session("area") = GetUserInfo(Usuario.Username, "Department")
                        Session("nombreU") = GetUserInfo(Usuario.Username, "displayname")
                        '  TextBox1.Text = GetUserInfo(Usuario.Username, "Phone")
                        'If Session("cargo") = "Socio" Or Session("cargo") = "Socio Internacional" Or Session("cargo") = "Director" Or Session("cargo") = "Gerente" Then
                        Session("sesion1") = True
                        Response.Redirect("index1.aspx")
                        'Else
                        '    Label3.Text = "Usted no Tiene Privilegios para Acceder a la Aplicación. Contacte a Tecnología"
                        'End If
                    ElseIf valor = False Then
                        Response.Redirect("default.aspx")
                    End If
                   
                End If
            Catch exp As Exception
                Label3.Text = exp.Message
                TextBox1.Text = ""
            End Try
        End Sub
       
       
        'codigo de Andy (Skullcrusher - Vbcity.com)
        Public Function GetUserInfo(ByVal inSAM As String, ByVal inType As String) As String
            Try
                'Dim sPath As String = "LDAP://" & Environment.GetEnvironmentVariable("USERDNSDOMAIN")
                Dim sPath As String = "LDAP://dc=atrame,dc=deloitte,dc=com"
                Dim SamAccount As String = inSAM.Substring(InStr(inSAM, "\"))
                Dim myDirectory As New DirectoryEntry(sPath)
                Dim mySearcher As New DirectorySearcher(myDirectory)
                Dim mySearchResult As SearchResult
                Dim myResultPropColl As ResultPropertyCollection
                Dim myResultPropValueColl As ResultPropertyValueCollection

                mySearcher.Filter = ("(&(objectClass=user)(samaccountname=" & SamAccount & "))")

                'Get the search result from the collection
                mySearchResult = mySearcher.FindOne

                'Get the Properites, they contain the usefull info
                myResultPropColl = mySearchResult.Properties

                'Retrieve the property your after
                myResultPropValueColl = myResultPropColl.Item(inType)
                Return CStr(myResultPropValueColl.Item(0))

            Catch ex As System.Exception
                Label3.Text = ex.ToString
            End Try
        End Function

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
           
        End Sub
    </script>

     

    do you need make a reference of system.directoryservices.dll in the "add reference" menu. ;)

    Saturday, February 11, 2006 1:42 PM
  • User1354132231 posted
    Hi Pablo - I don't see where you are authenticating a user here.  You are pulling some information about the user, but not authenticating them.  If you wanted to improve this code, you would only query AD one time to pull the information at once.  It is inefficient to query each time for only one piece of information.

    Tuesday, February 14, 2006 10:24 AM
  • User1354132231 posted

    Hello All,
      I am new to .NET development. i have installed VS.NET 2003. We are doing a project in that ther is a Login module where the users needs to be authenitcated. We are planning to use the users NT Login ID as the login to this asp page. This server will be hosted in the intranet of our office.

    First I would like to know if it would be possible to authenticate a user via ActiveDirectory. The user basically will be logging in the page like he would in the windows (username,pwd and domain).
    Also the site will be hosted in india (i our office) and users from other countries like Germany, JApan also would login to this. All these offices are inter connected via a corporate network. So i thnk i would be able to authenticate users from a different domain also.

    Can any one give me a sample on how this works? Or is there any better solution for this

    I am using .NET 2003 (ASP.NET 1.1)

    thanks in advance

    Karthik K


    I think this is a complicated problem.  I would suspect that your users are not all in the same domain (let alone the same forest) if they are so geographically dispersed.

    You can certainly authenticate them using either LDAP or something like SSP or LogonUser.  However, to use the latter methods, you would need to trust between all the domains.  I am guessing again that you don't have trusts between these forests or domains, right?

    To do this right, you should probably use LDAP authentication with SSL.  We have an example of how to do this in our book, but it is using .NET 2.0.

    Using the DirectoryEntry.Username and .Password will only get you so far because it does not scale well.
    Tuesday, February 14, 2006 11:03 AM
  • User387614326 posted

    Hi dunnry

    Hi Pablo - I don't see where you are authenticating a user here. 
    You are pulling some information about the user, but not authenticating them.
     If you wanted to improve this code, you would only query AD one time to pull
    the information at once.  It is inefficient to query each time for only one piece of information.

    :)

    is true, my error is not explain the code, Sorry, but I am a 100% newbie too...

    First.  I don't see where you are authenticating a user here. 

    this code has 2 textbox, the first the user, the second where the user "paste" the windows password.

    Dim username As String
                    Dim valor As String
                    username = TextBox1.Text
                    Dim fullPath As String = "LDAP://dc=atrame,dc=deloitte,dc=com"
                    Usuario = New DirectoryEntry(fullPath)
                    Usuario.Username = username 
                    Usuario.Password = TextBox2.Text
                    Usuario.RefreshCache()
                    valor = True 'User.Identity.IsAuthenticated   ' if this autentication has error is captured by 'the try catch and says the error, the "why"

    is true, my code is bad, n querys for n values for active directory is ridiculous, but I  dont know other efficient method?

    if the value is true, this refreshcache() event has no error, and your user and password is ok, in the forest. ( forest is the high level in the domain, units,groups,etc)

    If valor = True Then
                        '  Session("email") = GetUserInfo(Usuario.Username, "mail") ' query
                        Session("cargo") = GetUserInfo(Usuario.Username, "title") ' query
                        Session("area") = GetUserInfo(Usuario.Username, "Department") 'query
                        Session("nombreU") = GetUserInfo(Usuario.Username, "displayname") 'query
                        '  TextBox1.Text = GetUserInfo(Usuario.Username, "Phone")
                        'If Session("cargo") = "Socio" Or Session("cargo") = "Socio Internacional" Or Session("cargo") = "Director" Or Session("cargo") = "Gerente" Then
                        Session("sesion1") = True
                        Response.Redirect("index1.aspx")
                        'Else
                        '    Label3.Text = "Usted no Tiene Privilegios para Acceder a la Aplicación. Contacte a Tecnología"
                        'End If
                    ElseIf valor = False Then
                        Response.Redirect("default.aspx")
                    End If

    this code is the "guy" who send the querys to Active directory:

    Public Function GetUserInfo(ByVal inSAM As String, ByVal inType As String) As String
            Try
                'Dim sPath As String = "LDAP://" & Environment.GetEnvironmentVariable("USERDNSDOMAIN")
                Dim sPath As String = "LDAP://dc=atrame,dc=deloitte,dc=com"
                Dim SamAccount As String = inSAM.Substring(InStr(inSAM, "\"))
                Dim myDirectory As New DirectoryEntry(sPath)
                Dim mySearcher As New DirectorySearcher(myDirectory)
                Dim mySearchResult As SearchResult
                Dim myResultPropColl As ResultPropertyCollection
                Dim myResultPropValueColl As ResultPropertyValueCollection

                mySearcher.Filter = ("(&(objectClass=user)(samaccountname=" & SamAccount & "))")

                'Get the search result from the collection
                mySearchResult = mySearcher.FindOne

                'Get the Properites, they contain the usefull info
                myResultPropColl = mySearchResult.Properties

                'Retrieve the property your after
                myResultPropValueColl = myResultPropColl.Item(inType)
                Return CStr(myResultPropValueColl.Item(0))

            Catch ex As System.Exception
                Label3.Text = ex.ToString
            End Try
        End Function

     

    this line: mySearcher.Filter = ("(&(objectClass=user)(samaccountname=" & SamAccount & "))")

    is the filter, and you can change this is you wanna get other information, example, all the managers in the domain, etc. in this case is samaccountname why? password, guy.

    add the reference: <%@ Import Namespace = System.DirectoryServices %>, and the project explorer too.

     

    finally if you only to need autentication to active directory use this little code:

     Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Try
                Dim Usuario As New DirectoryEntry
                If TextBox1.Text = "" Then
                    Label3.Text = "Ingrese User"
                ElseIf TextBox2.Text = "" Then
                    Label3.Text = "Ingrese Password"
                Else
                    Dim username As String
                    Dim valor As String
                    username = TextBox1.Text
                    Dim fullPath As String = "LDAP://dc=atrame,dc=deloitte,dc=com"
                    Usuario = New DirectoryEntry(fullPath)
                    Usuario.Username = username  ' code important
                    Usuario.Password = TextBox2.Text  '  code important
                    Usuario.RefreshCache()   ' code important this is the line who to autenticate to active direct
                    valor = True 'User.Identity.IsAuthenticated
                   
                    'TextBox1.Text = ""
                    If valor = True Then
                          Response.Redirect("index1.aspx")
                        'Else
                        '    Label3.Text = "you cannot  to enter"
                        'End If
                    ElseIf valor = False Then
                        Response.Redirect("default.aspx")
                    End If
                   
                End If
            Catch exp As Exception
                Label3.Text = exp.Message
                TextBox1.Text = ""
            End Try
        End Sub
       

    this work better... not querys needed (tested in vb.net and asp.net and C#.net in .NET Framework 2.0)

    dunnry, sorry for post and dont explain this, my english is really bad, and sorry i offend you with this reply. 

    best regards my friend.

    Friday, February 17, 2006 12:37 AM
  • User-1332707980 posted

    Thank you very much guys. i will try this and will update this thread..

    regards

    Karthik K

    Friday, February 17, 2006 9:40 PM