Get logged in user from Active Directory and then get some of their AD attributes


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public UserPrincipal GetLoggedInUser()
  2. {
  3. try
  4. {
  5. //Get the principal logged in user
  6. WindowsPrincipal principal = System.Threading.Thread.CurrentPrincipal as WindowsPrincipal;
  7.  
  8. //split the principal identity name from the domain and put them in an array
  9. string delimiter = "\\";
  10. string userAndDomain = principal.Identity.Name.ToString();
  11. string[] arrayName = userAndDomain.Split(delimiter.ToCharArray());
  12.  
  13. //Get the context of this action based on the first item in the arrayName which is the domain
  14. PrincipalContext pc = new PrincipalContext(ContextType.Domain, arrayName[0]);
  15.  
  16. //Get the userprincipal (user) by matching the username in active directory and the name in the array
  17. UserPrincipal p = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, arrayName[1]);
  18.  
  19.  
  20. //make sure the userprincipal is a directoryentry then get the user
  21. if (p.GetUnderlyingObjectType() == typeof(DirectoryEntry))
  22. {
  23. DirectoryEntry user = (DirectoryEntry)p.GetUnderlyingObject();
  24.  
  25. //The EmpID is located in the wwwHomePage field in AD
  26. if (user.Properties["wwwHomePage"].Count > 0)
  27. {
  28. //set a variable to the wwwHomePage property so we can return it
  29. empID = Convert.ToInt32(user.Properties["wwwHomePage"].Value);
  30. }
  31. else
  32. {
  33. empID = 0;
  34. }
  35. }
  36. return p;
  37. }
  38. catch (Exception ex)
  39. {
  40.  
  41. return null;
  42. }
  43. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.