ASPX C# Search for a User in Active Directory - c#

Does anyone know the best way to search for a single user within Active Directory using DirectoryServices? I have code that currently lists all sub 'OU's' under a given LDAP path but I now want to add the feature of searching for a user under the path too. Could the code just be adapted to search for users?
I have included my code that lists all users in the current OU:
DirectoryEntry Ldap = new DirectoryEntry("LDAP://" + ouselect.SelectedValue + ";" + LDAPRoot, LDAPUser, LDAPPass);
DirectorySearcher ad_search = new DirectorySearcher(Ldap);
ad_search.Filter = "(objectClass=User)";
ad_search.SearchScope = SearchScope.Subtree;
ad_search.PropertiesToLoad.Add("samaccountname");
Any pointer that anyone can offer would be excellent.

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// do something here....
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!
PS: the PrincipalContext has a number of different overloads for its constructor - you can also define a username/password to use to query Active Directory, and you can also define a "starting" container, if you need to. Check out the MSDN documentation for details on this.

Your code is almost there. Just change your filter to search for a particular AD Attribute, rather than all users.
ad_search.Filter = string.Format("(department={0})", department);
ad_search.Filter = string.Format("(displayName={0})", "James Doe");
ad_search.Filter = string.Format("(sAMAccountName={0})", "some.username");

Related

How to make an exe file openable only by logging in an auth form

I need help to protect a very private tool that accepts followers on Instagram, I want to make the exe openable only if the user has logins credentials to prevent people from leaking it. I only have the .exe file and it's CMD line based, I wonder if we could like make an auth form in C# and then bind it to the .exe file
Thanks
Hard coded info:
The most simple scenario is just asking about credentials when starting the tool -> i.e. hard-coded username and password.
Active directory (or local PC) data:
other more professional option is to read the data from active directory (I do not know the environment you are working in), for example check if this user belongs to a specific group, the code will look like this:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAINNAME");
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");
if(user != null)
{
// check if user is member of that group
if (user.IsMemberOf(group))
{
// do something.....
}
}
The code above is taken from this answer.

Active Directory: How to determine whether account is service account?

Question: Is it possible to determine whether an account is a service account in Active Directory using C# LDAP? If yes, how?
Context: I have a program that is retrieving all objects of schema class type USER, GROUP, COMPUTER, FOREIGN SECURITY PRINCIPAL, and CONTACT. Currently, a service account is identified by string parsing the canonical name for 'service account'. I do not like this solution because string parsing is dependent on a folder location in the hierarchy that literally says 'service account'. It seems possible that a service account could be created and then placed in a folder path that does not include the string 'service account'. Unfortunately, I cannot test this because I am not an AD admin.
I have browsed around online without any luck so I am not sure if it is even possible.
Update:
Per Microsoft, it appears that the service account is contained in objectClass msDS-ManagedServiceAccount. However, when I set the DirectoryEntry filter to msDS-ManagedServiceAccount, no results are returned.
directoryEntry = new DirectoryEntry(strActiveDirectoryHost, null, null, AuthenticationTypes.Secure);
string strDsFilter = "(objectClass=msDS-ManagedServiceAccount)";
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry)
{
Filter = strDsFilter,
SearchScope = SearchScope.Subtree,
PageSize = intActiveDirectoryPageSize,
};
return searchResultCollection = directorySearcher.FindAll();
I have testing your code, and it does in fact return results in my environment. A few things to note:
Be sure that strActiveDirectoryHost is formatted correctly. The format should be LDAP://DC=contoso,DC=com
Check that you are searching from the root (or high enough to find the accounts you are looking for). MSAs are under the Managed Service Accounts container under the domain NC (i.e. LDAP://CN=Managed Service Accounts,DC=contoso,DC=com)
In my tests, I call new DirectoryEntry() with only the path. Not sure if passing AuthenticationTypes.Secure is causing an issue for you
The objectClass you have is correct.
So I am working on this to get the MSA as well as create them. I am able to get the MSA using the System.DirectoryServices.AccountManagement namespace, still working on creating it (unsure if this is really possible)
But for finding the accounts which are MSAs you can use the below code
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword);
GroupPrincipal currentGroup = GroupPrincipal.FindByIdentity(oPrincipalContext, "YourGroupName");
foreach (Principal a_principal in currentGroup.GetMembers())
{
if (a_principal.StructuralObjectClass == "msDS-ManagedServiceAccount")
{
Console.Write(a_principal.SamAccountName); //To get the name
ComputerPrincipal oComputerPrincipal = ComputerPrincipal.FindByIdentity(oPrincipalContext, a_principal.Name); //creating a computerprincipal to get more details about the MSA
}
}
You can use the above logic and create a Principal for the user account and get the structural object class for that account to find out if it is MSA.
Something like this:
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
if (oUserPrincipal.StructuralObjectClass == "msDS-ManagedServiceAccount")
{
Console.Write(oUserPrincipal.SamAccountName); //To get the samaccountname
}

C# get groups that a user is a member of in Active Directory

I'm not a programmer by nature so I apologize in advance :) I'm using the code snippets from http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C#39 and it has been really helpful. I'm using his method for getting user group memberships and it requires his AttributeValuesMultiString method as well. I don't have any syntax errors but when I call the Groups method via Groups("username", true) I get the following error:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in System.DirectoryServices.dll
I have done some digging but nothing seems to really answer why I'm getting this error.
You should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// get the user's groups
var groups = user.GetAuthorizationGroups();
foreach(GroupPrincipal group in groups)
{
// do whatever you need to do with those groups
}
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!

Delete user in active directory using c#

I've written some code but not works it throws Exception "An operations error occurred."
code --->
DirectoryEntry dirEntry = new DirectoryEntry("LDAP path", "admin-username", "admin-password");
dirEntry.Properties["member"].Remove("username-delete");
dirEntry.CommitChanges();
dirEntry.Close();
give me some ideas to get out of this things..
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find the user you want to delete
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
user.Delete();
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!
When you are already using a DirectoryEntry there is no need for PrincipalContext or UserPrincipal.
You can simply use the DeleteTree() method:
DirectoryEntry dirEntry = new DirectoryEntry("LDAP path", "admin-username", "admin-password");
dirEntry.DeleteTree();

Querying LDAP for Usergroup of Specific User

I have to check usergroups of LDAP Active Directory for a specific user in C#. Mean I pass this username to a method and it returns me list of group from that user belongs. Can You Please help me in this. Im Searching alot But Everytime get new error.
LDAP Path: 192.168.1.4
Domain Name: Arslan
UserName: ArslanP
Password: testad
Since you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
Basically, add a reference to the assembly System.DirectoryServices.AccountManagement, and then you can define a domain context and easily find users and/or groups in AD:
using System.DirectoryServices.AccountManagement;
public List<GroupPrincipal> GetGroupsForUser(string username)
{
List<GroupPrincipal> result = new List<GroupPrincipal>();
// set up domain context - if you do a lot of requests, you might
// want to create that outside the method and pass it in as a parameter
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find user by name
UserPrincipal user = UserPrincipal.FindByIdentity(username);
// get the user's groups
if(user != null)
{
foreach(GroupPrincipal gp in user.GetAuthorizationGroups())
{
result.Add(gp);
}
}
return result;
}
The new S.DS.AM makes it really easy to play around with users and groups in AD:
This related question may help you:
Get List of Users From Active Directory In A Given AD Group
It asks the reverse question, which is how to qet a list of users when you know the group, but other answers may be of use to you as well.
See also the answer to this question:
How to get all the AD groups for a particular user?

Categories

Resources