C # access to active directory with different user credentials

There is a new application for creating users that we just provided to our users. However, these users need the ability to create users through the application, even if they themselves do not have the right to create users.

In C #, how do you personalize another user to have this functionality. This is the main application using System.DirectoryServices .

Code snippet:

 DirectoryEntry dEntry = new DirectoryEntry("LDAP://OU="); DirectorySearcher dSearcher = new DirectorySearcher(dEntry); //filter just user objects dSearcher.SearchScope = SearchScope.Subtree; dSearcher.Filter = "(&(objectClass=user)(mail=" + excel_Holding_Table.Rows[i]["EmailAddress"].ToString() + "))"; dSearcher.PageSize = 1000; sResults = dSearcher.FindAll(); 
+6
source share
4 answers

You can directly use the DirectoryEntry class and specify a username and password:

 DirectoryEntry de = new DirectoryEntry(path); de.Username = "username"; de.Password = "password"; 

And access Active Directory from an object. Or you can use the WindowsIdentity class and impersonate the user:

 WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()); WindowsImpersonationContext impersonatedUser = newId.Impersonate(); )); WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()); WindowsImpersonationContext impersonatedUser = newId.Impersonate(); 

A complete sample code is available at:

Avatar and DirectoryEntry

+9
source

Use the DirectoryEntry constructor, which accepts username, password, and authentication parameters .

Aside, the types DirectoryEntry DirectorySearcher and SearchResultCollection IDisposable - you need to destroy them, possibly with using instructions.

0
source

Use the DirectoryEntry constructor (String, String, String, AuthenticationTypes), which uses a username and password instead of impersonation.

 DirectoryEntry directoryEntry = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/Root", @"domain\username", "password", AuthenticationTypes.Secure | AuthenticationTypes.Sealing); 

Link

0
source

You can use privileged credentials to connect to AD or to impersonate a privileged user, as other answers suggested.

But this has security implications, as it means that your users will be able to use these privileged credentials for other, unauthorized purposes.

A safer solution is to create a web service that runs under a service account with the appropriate AD permissions. Users can authenticate with the web service using Windows authentication, and the web service will create users on their behalf. He can use authorization to limit what users are allowed to do (for example, only create users in his own department).

0
source

Source: https://habr.com/ru/post/916588/


All Articles