Skip to content

Instantly share code, notes, and snippets.

@davegreen
Last active December 27, 2015 02:29
Show Gist options
  • Save davegreen/7253114 to your computer and use it in GitHub Desktop.
Save davegreen/7253114 to your computer and use it in GitHub Desktop.
/// <summary>
/// Gets the DirectoryEntry object of the LDAP distinguishedname passed in, using the current user credentials.
/// </summary>
/// <param name="path">A distinguishedname of the object you wish to get the DirectoryEntry for.</param>
/// <returns></returns>
private static DirectoryEntry GetDirectoryEntry(string path)
{
DirectoryEntry de = new DirectoryEntry();
de.Path = path;
de.AuthenticationType = AuthenticationTypes.Secure;
return de;
}
/// <summary>
/// Checks and returns a boolean value on whether the attribute passed in as a parameter can be modified on the user.
/// </summary>
/// <param name="user">The DirectoryEntry object of a user to check to see if the current user can write to the specified attribute.</param>
/// <param name="attributeSet">The string of the attribute to check.</param>
/// <returns>A boolean value indicating read-only (false) or writable (true).</returns>
private bool CheckAttribWritable(DirectoryEntry user, string attribute)
{
user.RefreshCache(new string[] {"allowedAttributesEffective"});
return (user.Properties["allowedAttributesEffective"].Contains(attribute));
}
/// <summary>
/// Checks and returns a boolean value on whether the attributes passed in as a parameter can be modified on the user.
/// </summary>
/// <param name="user">The DirectoryEntry object of a user to check to see if the current user can write to the specified attributes.</param>
/// <param name="attributeSet">The string array of attributes to check.</param>
/// <returns>A boolean value indicating all attributes are writable (true), or not (false).</returns>
private bool CheckAttribWritable(DirectoryEntry user, string[] attributeSet)
{
// The allowedAttributesEffective AD attribute contains the list of attributes the user can modify.
// We check for the all the attributes specified in attributeSet to see if we can write to them.
// If all the attributes in attributeSet exist within allowedAttributesEffective true is returned.
user.RefreshCache(new string[] {"allowedAttributesEffective"});
return attributeSet.All(attribute => user.Properties["allowedAttributesEffective"].Contains(attribute));
}
DirectoryEntry userDE = GetDirectoryEntry("LDAP://CN=User,OU=Users,DC=contoso,DC=local");
bool allowed = CheckAttribWritable(userDE, "lockoutTime");
string[] attributes = { "displayName", "givenName", "sn", "lockoutTime" };
bool allowedmore = CheckAttribWritable(userDE, attributes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment