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.
<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> |
using System.Configuration; using System.DirectoryServices; | |
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(); } |
<connectionStrings> <add name="ADConnection" connectionString="LDAP://ads.your.site.com"/> </connectionStrings > |
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 Email
|
|||
|
|

Subscribe by RSS
Subscribe by Email
17 comments :
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!
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?
That solved my problem thanks man
Very Nice article.
Thanks for your help.
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
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
Thanks alot. It saves my time.
- M. A. Khan
Thank you very much. I searched all day for this solution!
Thanks so much.This is step by step doc.
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();
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
helo sir using system.DirectorySearcher namespace im not geting on my page...please help its urgent
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
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.
Hi,
How to get the defined properties of Active directory parameter like ....“givenName” and for lastname I used “sn”
AWSM BLOSM...10 STARS !!!! THAnks yaar
Hi All,
Use this if you want only manager
lblman.Text = dsresult.Properties["manager"][0].ToString().Split (',')[0].Split ('=')[1];
Thanks