I am writing a permissions system for my WPF application that needs to work with both Active Directory and local machine accounts; the system may or may not be connected to a network.
The user can log into the application with either an AD login or a local machine login. The application stores data in an SQL Server Express data base and each row will have an "owner".
The application will only show rows that are "owned" by the logged in user.
Per this question, the recommended data to store to identify a user is the LDAP objectGUID
which I can retrieve with the code below and store in a uniqueidentifier column.
using System.DirectoryServices.AccountManangement;
using System.Security.Principal;
public class ActiveDirectoryHelper
{
public static Guid? GetObjectGuidFromIdentity(WindowsIdentity identity)
{
string domainName = identity.Name.Split('\\')[0];
PrincipalContext pc = null;
if (domainName == Environment.MachineName)
{
pc = new PrincipalContext(ContextType.Machine);
}
else
{
pc = new PrincipalContext(ContextType.Domain, domainName);
}
UserPrincipal user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, identity.Name);
return user.Guid;
}
}
However, UserPrincipal.Guid
is null for ContextType.MachineName
.
Is there a single piece of information that I can store that can refer to either an AD account or a local account ?
Or do I need to add another column to specify the directory type (AD/SAM) and use another column to store a different identifier (SID) ?