C# accessing active directory with different user

2019-02-17 08:17发布

There is a new user creation application that we have just provided our users. However these users need the ability to creation users through the application even though they themselves do not have permission to create users.

In C# how do you impersonate another user in order to have this functionality. This application primary 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();

4条回答
混吃等死
2楼-- · 2019-02-17 08:54

Use the DirectoryEntry constructor that takes username, password and authenticationType parameters.

As an aside, the DirectoryEntry DirectorySearcher and SearchResultCollection types are IDisposable - you need to dispose them, probably with using statements.

查看更多
Deceive 欺骗
3楼-- · 2019-02-17 08:58

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

But this has security implications, since it means your users would be able to use these privileged credentials for other, non-authorized, purposes.

A more secure solution would be to create a web service that runs under a service account with appropriate AD permissions. Users can authenticate to the web service using Windows authentication, and the web service would create users on their behalf. It could use authorization to restrict what users are allowed to do (e.g. only create users in their own department).

查看更多
别忘想泡老子
4楼-- · 2019-02-17 09:11

Use the DirectoryEntry Constructor (String, String, String, AuthenticationTypes) that takes a username and password instead of impersonation.

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

Reference

查看更多
放我归山
5楼-- · 2019-02-17 09:13

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

DirectoryEntry de = new DirectoryEntry(path);

de.Username = "username";
de.Password = "password";

And access Active Directory from the de object. Or you can use the WindowsIdentity class and and impersonate a User:

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

A full code sample is available at:

Impersonation and DirectoryEntry

查看更多
登录 后发表回答