ASP.NET w/ VB Getting UserName after isAuthenticated from Active Directory

Posted on 2009-04-28
Last Modified: 2012-05-06
I have three issues that I am struggling with in my code for authenticating users in AD.

1. I want to pass the Username to the next page so that I can use it in an Audit Trail later on during the users experience with the app.  I do not want to use a query string.  

2. I want to get the users First and Last Name after authenticating.  I have no clue how to do this and no clear explanation on the web has been found.

3. I want the user to be a member a specific group in AD.  I am using LDAP

Can anyone help me thorugh these issues?  I have included my code below - works fine except that any member of the domain can login..not just members of the group

 I am assuming that the majority of the code needs to go here except for the username,etc that will passed off to the next page.

I have this for getting at the specific group but I can not figure out how to use this in my code.  As is - does not work.
LDAP:// Managed Users,OU=Users,OU=MySite,OU=ABC, DC=my,DC=domain,DC=org

imports System

imports System.Web.Security

imports System.Security.Principal

imports System.Web

imports System.DirectoryServices

imports System.DirectoryServices.DirectoryEntry

Partial Class Authenticate_With_Active_Directory

            Inherits System.Web.UI.Page


            Protected Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click

                Dim isAuthenticated As Boolean = AuthenticateUser()

                If isAuthenticated Then

                   Dim sScript As String

                   Dim cScript As String


        sScript = "<SCRIPT Language=JavaScript> newWin = window.location.href='/default.aspx'; </SCRIPT>"

        RegisterStartupScript("NewWindow", sScript)

        cScript = "<script language='javascript'> { window.close() }</script>"           





                    Incorrect.visible = True

                End If

            End Sub


            Private Function ValidateActiveDirectoryLogin(ByVal Domain As String, ByVal Username As String, ByVal Password As String) As Boolean

                Dim Success As Boolean = False

                Dim Entry As New System.DirectoryServices.DirectoryEntry("LDAP://" & Domain, Username, Password)

                Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)

                Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel


     			Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne

     			Success = Not (Results Is Nothing)

     			Dim aCookie As New HttpCookie("lastVisit")

     			aCookie.Values("userName") = txtUserName.Text

     			aCookie.Values("lastVisit") = DateTime.Now.ToString()

     			aCookie.Expires = DateTime.Now.AddHours(4)



     			Success = False

		End Try

                Return Success

            End Function


            Private Function AuthenticateUser() As Boolean

                Dim username As String = txtUsername.Text

                Dim password As String = txtPassword.Text

                Dim domain As String = ""


                Dim isAuthenticated As Boolean = ValidateActiveDirectoryLogin(domain, username, password)


                Return isAuthenticated


            End Function


        End Class

Open in new window

Question by:aninec
    LVL 8

    Accepted Solution

    You can restrict access to your site, or a section of your site, by AD Groups by specifying them in the web.config:
          <allow roles="RoleA" />  
          <deny users="*" />  

    To get the login name of the currently authenticated user:

    LVL 8

    Expert Comment

    To get the First and Last Name out of Directory you'll want to take a look at the documentation for System.DirectoryServices. (Note:  To use this NameSpace, you'll need to manually add a reference to you're project to the System.DirectoryServices.dll).

    PrincipalContext pContext = new PrincipalContext(ContextType.Domain);

    Principal p = Principal.FindByIdentity(pContext, IdentityType.SamAccountName, System.Web.HttpContext.Current.User.Identity.Name);

    //Got an instance to a managed reference of the AD Account
    DirectoryEntry dirEntry = (DirectoryEntry)p.GetUnderlyingObject();

    string FirstName = dirEntry.Properties["FirstName"];
    string LastName = dirEntry.Properties["LastName"];

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
    Do you have users whose passwords are expiring and they are constantly calling you?  Well I sure did and needed a way to put an end to this.  We have a lot of remote users which would not be notified that their passwords were expiring since they wer…
    This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles from a Windows Server 2008 domain controller to a Windows Server 2012 domain controlle…
    This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now