Effortless User Experience

Accessing User Information with .NET and Windows Authentication

In an ASP.Net page, you can easily retrieve the username of the currently logged in user using Request.ServerVariables(“AUTH_USER”). However, if you need to obtain additional information such as the user’s real name (the “Display Name” in Active Directory), there are a few more steps involved. In this blog post, we will explore how to retrieve the Display Name of the currently logged in user using .NET and Windows Authentication.

Prerequisites

————-

To use the code snippet provided below, you will need to meet the following prerequisites:

1. .NET 2: The code is written in VB.NET, so you will need to have .NET 2 installed on your system.

2. Windows Authentication: Access to the page in IIS must be controlled via Windows Authentication. This means that users must be logged in to their Windows accounts in order to access the page.

3. System.DirectoryServices reference: The code uses the System.DirectoryServices namespace, so you will need to add a reference to this assembly in your Web.Config file.

Retrieving the Display Name

————————-

To retrieve the Display Name of the currently logged in user, you can use the following code snippet:

“`

Dim username As String = Request.ServerVariables(“AUTH_USER”)

Dim domain As String = Request.ServerVariables(“AUTH_DOMAIN”)

Dim user As DirectoryEntry = New DirectoryEntry(String.Format(“LDAP://{0}/{1}”, domain, username), “Authentication”)

Dim displayName As String = user.Properties(“displayName”).Value.ToString()

“`

This code first retrieves the username and domain of the currently logged in user using Request.ServerVariables(“AUTH_USER”) and Request.ServerVariables(“AUTH_DOMAIN”), respectively. It then creates a new DirectoryEntry object for the user, using the LDAP protocol to connect to the Active Directory server. Finally, it retrieves the user’s Display Name from the Active Directory using the Properties collection of the DirectoryEntry object.

The displayName variable now contains the Display Name of the currently logged in user. You can use this variable in your ASP.Net page as needed.

Conclusion

———-

In this blog post, we have explored how to retrieve the Display Name of the currently logged in user using .NET and Windows Authentication. We have also discussed the prerequisites for using the code snippet provided above. By following the steps outlined in this post, you can easily access additional information about the currently logged in user beyond their username.