[Last Call] Learn how to a build a cloud-first strategyRegister Now


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

Posted on 2009-04-28
Medium Priority
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://my.domain.org/CN=OU=ABC 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 = "my.domain.org"
                Dim isAuthenticated As Boolean = ValidateActiveDirectoryLogin(domain, username, password)
                Return isAuthenticated
            End Function
        End Class

Open in new window

Question by:aninec
  • 2

Accepted Solution

ppittle earned 2000 total points
ID: 24254343
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:


Expert Comment

ID: 24254458
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"];

Featured Post

Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Compliance and data security require steps be taken to prevent unauthorized users from copying data.  Here's one method to prevent data theft via USB drives (and writable optical media).
It’s time for spooky stories and consuming way too much sugar, including the many treats we’ve whipped for you in the world of tech. Check it out!
This tutorial will walk an individual through the steps necessary to join and promote the first Windows Server 2012 domain controller into an Active Directory environment running on Windows Server 2008. Determine the location of the FSMO roles by lo…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Suggested Courses

829 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