Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current user's Active Directory details in C#

I am working on an C# and ASP.Net application, that uses Windows Authentication.

i.e. in Web.config:

<system.web>     <authentication mode="Windows" /> </system.web> 

I want to get details for the current user (full name, email address, etc) from Active Directory.


I can get their pre Windows 2000 user login name (eg: SOMEDOMAIN\someuser) by using

string username = HttpContext.Current.Request.ServerVariables["AUTH_USER"]; 

I've worked out the LDAP query for the user, using their current login name (not their pre Windows 2000 user login name):

DirectorySearcher adSearch = new DirectorySearcher(         "([email protected])"); SearchResult adSearchResult = adSearch.FindOne(); 

However, I don't know how to either search AD for the user using their pre W2K login name, or get their login name in the '[email protected]' format.

Any ideas?

like image 240
Sophia Avatar asked Mar 12 '09 05:03

Sophia


People also ask

How do I get the current UserName in .NET using C #?

GetCurrent(). Name; Returns: NetworkName\Username.

What gives domain UserName of the current user of the local machine?

Use the UserDomainName property to obtain the user's domain name and the UserName property to obtain the user name. On Unix platforms the UserName property wraps a call to the getpwuid_r function. If an ASP.NET application runs in a development environment, the UserName property returns the name of the current user.

How can I see logged in UserName in asp net?

User property in ASP.Net MVC Razor. In this article I will explain with an example, how to display Welcome Username after Login in ASP.Net MVC Razor. The Login Form will be implemented using Forms Authentication and Entity Framework and the Username will be displayed using the HttpContext.


1 Answers

The "pre Windows 2000" name i.e. DOMAIN\SomeBody, the Somebody portion is known as sAMAccountName.

So try:

using(DirectoryEntry de = new DirectoryEntry("LDAP://MyDomainController")) {    using(DirectorySearcher adSearch = new DirectorySearcher(de))    {      adSearch.Filter = "(sAMAccountName=someuser)";      SearchResult adSearchResult = adSearch.FindOne();    } } 

[email protected] is the UserPrincipalName, but it isn't a required field.

like image 64
Alan Avatar answered Sep 21 '22 09:09

Alan