Skip to content

Instantly share code, notes, and snippets.

@rchacon
Created March 13, 2015 03:19
Show Gist options
  • Save rchacon/ef36d217261fb06681bb to your computer and use it in GitHub Desktop.
Save rchacon/ef36d217261fb06681bb to your computer and use it in GitHub Desktop.
Validate and Search against Active Directory
namespace api_v1_csharp.Models.ldap
{
using System;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
using System.Collections.Generic;
public class UsersRepository : IUsersRepository
{
public bool ValidateCredentials(string username, string password)
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
return pc.ValidateCredentials(username, password);
}
}
public User Get(string username)
{
ActiveDirectorySite adSite = ActiveDirectorySite.GetComputerSite();
Forest forest = Forest.GetCurrentForest();
GlobalCatalog globalCat = forest.FindGlobalCatalog(adSite.Name);
DirectorySearcher dirSearcher = globalCat.GetDirectorySearcher();
dirSearcher.CacheResults = false;
dirSearcher.ReferralChasing = ReferralChasingOption.All;
dirSearcher.SearchScope = SearchScope.Subtree;
dirSearcher.Filter = String.Format("(&(objectcategory=person)(samaccountname={0}))", username);
try
{
using (DirectoryEntry entry = dirSearcher.FindOne().GetDirectoryEntry())
{
User user = new User();
user.samaccountname = username;
user.distinguishedname = entry.Properties["distinguishedname"][0].ToString();
user.displayname = entry.Properties["displayname"][0].ToString();
user.mail = entry.Properties["mail"][0].ToString();
user.memberOf = "";
// some students don't have these properties ie. mcdowe623
try
{
user.givenname = entry.Properties["givenname"][0].ToString();
user.sn = entry.Properties["sn"][0].ToString();
}
catch (Exception)
{
user.givenname = "";
user.sn = "";
}
string cn;
user.groups = new List<string>();
foreach (string group in entry.Properties["memberOf"])
{
// Client applications already depend on 'memberOf'
user.memberOf += group.ToString() + ";";
cn = group.ToString().Split(',')[0].Split('=')[1];
user.groups.Add(cn);
}
return user;
}
}
catch (Exception)
{
return null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment