Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

how to get userdetails from Active Directory based on username using asp.net

Mar 11, 2011
Introduction:

Here I will explain how to get userdetails from Active directory based on username using asp.net

Description:

One day I got requirement like to get user details from Active directory based on username.

For that first create one new website after that right click on website and select Add Reference option after that select System.DirectoryServices from .NET tab and click ok now directory services reference has added to our application do you know why we have added this directory service to our application because by using this service we can get userdetails from Active directory.

After that design your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Enter Username:
</td>
<td>
<asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
<tr>
<td align="right">
First Name:
</td>
<td>
<asp:Label ID="lblfname" runat="server" Font-Bold="true"></asp:Label> 
</td>
</tr>
<tr>
<td align="right">
Last Name:
</td>
<td>
<asp:Label ID="lbllname" runat="server" Font-Bold="true" ></asp:Label> 
</td>
</tr>
<tr>
<td align="right">
Email:
</td>
<td>
<asp:Label ID="lblemail" runat="server" Font-Bold="true"></asp:Label> 
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
After that add these references in code behind

using System.Configuration;
using System.DirectoryServices;

After completion of writing namespaces and write the following code in button click codebehind


protected void btnSubmit_Click(object sender, EventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["ADConnection"].ToString();
DirectorySearcher dssearch = new DirectorySearcher(connection);
dssearch.Filter = "(sAMAccountName=" + txtusername.Text + ")";
SearchResult sresult = dssearch.FindOne();
DirectoryEntry dsresult = sresult.GetDirectoryEntry();
lblfname.Text = dsresult.Properties["givenName"][0].ToString();
lbllname.Text = dsresult.Properties["sn"][0].ToString();
lblemail.Text = dsresult.Properties["mail"][0].ToString();
}
If you observe above code here I am getting active directory connection path from web.config for that set the active directory connection in web.config like this

<connectionStrings>
<add name="ADConnection" connectionString="LDAP://ads.your.site.com"/>
</connectionStrings >
Demo


If you observe above code to get firstname i used givenName” and for lastname I used sn”  these all are defined properties in active directory if we want to get the details address, work phone, home address etc each one having different LDAP property name check below table for LDAP property names in Active directory

Name
LDAP Provider Property Name
Syntax
First Name
givenName
String
Initials
initials
String
Last name
sn
String
Display name
displayName
String
Description
description
String
Office
physicalDeliveryOfficeName
String
Telephone number
telephoneNumber
String
Other Telephone numbers
otherTelephone
String
E-mail
mail
String
Web page
wWWHomePage
String
Other Web pages
url
String
Street
streetAddress
String
P.O. Box
postOfficeBox
String
City
l
String
State/province
st
String
Zip/Postal Code
postalCode
String
Country/region
c, co, countryCode
String
User logon name
userPrincipalName
String
pre-Windows 2000 logon name
sAMAccountName
String
Account disabled?
userAccountControl
Boolean
User Profile path
profilePath
String
Logon script
scriptPath
String
Home folder, local path
homeDirectory
String
Home folder, Connect, Drive
homeDrive
String
Home folder, Connect, To:
homeDirectory
String
Title
title
String
Department
department
String
Company
company
String
Manager
manager
String
Mobile
mobile
String
Fax
facsimileTelephoneNumber
String
Notes
info
String

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

29 comments :

Unknown said...

Thanks very much for this post! Though your code is C based and I'm working in VB, I was able to piece together this code and get it working in my application. I have found a way to use this to automatically pull user information from the logged in user. In the Master page of my site I used this code:

Dim nLen As Integer
Dim connection As String
Dim dssearch As System.DirectoryServices.DirectorySearcher
Dim sresult As System.DirectoryServices.SearchResult
Dim dresult As System.DirectoryServices.DirectoryEntry

nLen = Len(Page.User.Identity.Name)
Session("UserName") = ""
Session("UserName") = Mid(Page.User.Identity.Name, 15, nLen)

connection = ConfigurationManager.ConnectionStrings("ADConnection").ToString()
dssearch = New System.DirectoryServices.DirectorySearcher(connection)
dssearch.Filter = "(sAMAccountName=" + Session("UserName") + ")"
sresult = dssearch.FindOne()
dresult = sresult.GetDirectoryEntry()

lblName.Text = dresult.Properties("displayName").Value.ToString()

Hope this helps anyone working in VB!

Anonymous said...

Very nice article.

Is there any way to use a such script to validate a username/password to receive either true or false as a Valid AD login attempt?

Anonymous said...

That solved my problem thanks man

Anonymous said...

Very Nice article.

Thanks for your help.

Anonymous said...

Dear Suresh

I received the following error message after keying in username and click Submit. What could be the source of error. I have followed the steps as decribed above. Thanks in advance.

erah






Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Source Error:


Line 23: DirectoryEntry dsresult = sresult.GetDirectoryEntry();
Line 24: lblfname.Text = dsresult.Properties["givenName"][0].ToString();
Line 25: lbllname.Text = dsresult.Properties["sn"][0].ToString();
Line 26: lblemail.Text = dsresult.Properties["mail"][0].ToString();
Line 27: }


Stack Trace:


[ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index]
System.Collections.CollectionBase.System.Collections.IList.get_Item(Int32 index) +9551843
System.DirectoryServices.PropertyValueCollection.get_Item(Int32 index) +8
HR_StaffCV_FindADdetails.btnSubmit_Click(Object sender, EventArgs e) in d:\KH-INTRA-DEV3\HR\StaffCV\FindADdetails.aspx.cs:25
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563




--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272

Anonymous said...

I got it resolved after searching the net. The reason for the error is my active directory entry does not have a last name entry. Just uncommnet this lbllname.Text = dsresult.Properties["sn"][0].ToString(); and the error message goes way. Thanks Suresh for this wonderful post.
erah

Anonymous said...

Thanks alot. It saves my time.

- M. A. Khan

Anonymous said...

Thank you very much. I searched all day for this solution!

Anonymous said...

Thanks so much.This is step by step doc.

Gopal Arora said...

Hi suresh,

I have done the same code for directory search. No error is coming when i run this in browser, but results are not coming.

string connection = ConfigurationManager.ConnectionStrings["dbcon"].ToString();
DirectorySearcher dssearch = new DirectorySearcher(connection);
dssearch.Filter = "(name=" + txtusername.Text + ")";
SearchResult sresult = dssearch.FindOne();
DirectoryEntry dsresult = sresult.GetDirectoryEntry();
lblfname.Text = dsresult.Properties["name"][0].ToString();
lbllname.Text = dsresult.Properties["lname"][0].ToString();
lblemail.Text = dsresult.Properties["mail"][0].ToString();

pavan said...

Good One, i have a question here, say for example when user logs in from active directory username & password of a particular country, i have to save the files on country basis in sqlserver table. Could you please advise on this

Unknown said...

helo sir using system.DirectorySearcher namespace im not geting on my page...please help its urgent

Anonymous said...

hi, when I try the manager variable, i get CN=test01,OU=MIS1 Dept,OU=greyt,DC=silver,DC=COM

I just want the test01 to appear

Unknown said...

Hi,

I am trying to implement the same, and want to share the problem faced:

Users in my AD are bound to their computers. Now I want to implement a switch user functionality in my VB .NET application, where in the user will enter his username and password into the site open on a machine on which he/she does not have access. This method fails to authenticate the user giving a bad username/password error when we execute the FindOne() method.

Otherwise, the users are able to authenticate themselves from their individual bound machines.

Any help provided will be greatly appreciated.

anandakumar said...

Hi,
How to get the defined properties of Active directory parameter like ....“givenName” and for lastname I used “sn”

Varun Verma said...

AWSM BLOSM...10 STARS !!!! THAnks yaar

Varun Verma said...

Hi All,

Use this if you want only manager

lblman.Text = dsresult.Properties["manager"][0].ToString().Split (',')[0].Split ('=')[1];

Thanks

bhargava said...

Nice blog,

All properties are coming except phone number

Anonymous said...

DirectorySearcher dssearch = new DirectorySearcher(connection); works on local development environment but fails when I host it on a server. I need to provide my active directory user id and password to this line so that it can work like:-
DirectorySearcher dssearch = new DirectorySearcher(connection,"abhas","Password123").
Is there any way I can avoid entering my credentials and still running the application

Rehan Hussain said...

great, this is what i was looking for.
Thanks

Eder Juarez said...

a que se debe este error agradeceria si alguien tiene una solucion :)

{System.Runtime.InteropServices.ExternalException} = {"El dominio especificado no existe o no se pudo poner en contacto con él.\r\n"}

Anonymous said...

Will you please write this code LDAP with WCF

Anonymous said...

HI Suresh,

how to get userdetails from Active Directory based on given username using java scirpt
for nintex form 2010
pls send me java script
thanks and regards
raju

Anonymous said...

Very useful

KAmlesh said...

Hi, Could you please let me know what kind of IIS setting required to host this, because after hosting this I am not getting AD details.

Anonymous said...

Thanks for this easy to use example !

Anonymous said...

How to get all Active users in AD..?
Pls Help Sir

andra said...

fedsaf

andra said...

Good 1

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.