Skip to content

Instantly share code, notes, and snippets.

@sandcastle
Last active August 29, 2015 14:01
Show Gist options
  • Save sandcastle/d818335a9321d6c8422d to your computer and use it in GitHub Desktop.
Save sandcastle/d818335a9321d6c8422d to your computer and use it in GitHub Desktop.
Helper for accessing the always unique Active Directory user ID (ObjectGUID).
public class AdHelper
{
public WindowsAccount GetWindowsAccount(string username = "")
{
// NOTE: If the username is not specified, use the current users account
// The username should also include the domain if available
var identity = String.IsNullOrWhiteSpace(username)
? WindowsIdentity.GetCurrent().Name
: username;
try
{
var objGuidBytes = (Byte[]) GetUserFromAd(identity).Properties["objectGUID"][0];
return new WindowsAccount(identity, new Guid(objGuidBytes));
}
catch (Exception exception)
{
return new WindowsAccount();
}
}
static SearchResult GetUserFromAd(string samAccountName)
{
var directory = new DirectorySearcher();
var cleansedAccountName = StripDomainName(samAccountName);
var filter = string.Format("(&(objectCategory=user)(objectClass=user)(|(samaccountname={0})))", cleansedAccountName);
directory.Filter = filter;
directory.SizeLimit = int.MaxValue;
directory.CacheResults = true;
directory.PropertiesToLoad.AddRange(new[] { "objectGUID", "sAMAccountName" });
var searchResult = directory.FindOne();
return searchResult;
}
static string StripDomainName(string username)
{
var lastInstanceOfForwardSlash = username.LastIndexOf('\\');
if (lastInstanceOfForwardSlash > -1 && username.Length > username.LastIndexOf('\\') + 1)
{
return username.Substring(lastInstanceOfForwardSlash + 1);
}
return username;
}
}
public class WindowsAccount
{
public WindowsAccount()
: this(String.Empty, Guid.Empty) { }
public WindowsAccount(
string name,
Guid objectId)
{
Name = name;
ObjectId = objectId;
}
public string Name { get; private set; }
public Guid ObjectId { get; private set; }
public bool IsValid
{
get { return ObjectId != Guid.Empty; }
}
public override string ToString()
{
return String.Format("{0} ({1:D})", Name, ObjectId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment