Unable to extract information - c#

I'm trying to query a domain to determine if:
User is a valid user (and has the correct password)
User is enabled
User belongs to group x
My development machine does not belong to this domain.
I want to specify the username and password via my application
I'm using the System.DirectoryServices.AccountManagement namespace as this seems to be the most efficient way doing this, however I've struggling to get even the most basic of information out of my domain controller.
I can explore LDAP via another tool.
First test is to collect user information, the code below returns null on user.
The user however is valid.
What am I doing wrong?
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "server","CN=Users,DC=doom,DC=home", "ldapuser","password");
// get user contect
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.Name, username);
//is user locked?
var locked = user.Enabled;
Update:
Having defined the bind method as below, I now receive error
"Information about the domain could not be retrieved (1355)."
var ctx = new PrincipalContext(ContextType.Domain, "server", "DC=doom,DC=home", ContextOptions.SimpleBind, "ldapuser", "password");

Sorted.
This answer resolves the two issues I came across when attempting to connect to a domain controller that I am not a member of.
This article get me the final answer:
http://elegantcode.com/2009/03/21/one-scenario-where-the-systemdirectoryservices-accountmanagement-api-falls-down/
you need to define the Bind in the context (i.e. ContextOptions.SimpleBind)
You must set up the domain server in your Network adaptors DNS settings as the first DNS server to use.
I can now connect to my AD and collect data.

Related

How to get down-level logon name from UserPrincipal in .Net

I have the following search query where I use a User Principal Name identification:
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
var user = UserPrincipal.FindByIdentity(principalContext, IdentityType.UserPrincipalName, "user1#domain1.local"); //the searched UPN will be dynamic!
After I get the UserPrincipal object, I have to create a down-level logon format (domain1\user1).
Unfortunately I have the following distinguished name:
CN=User One,OU=Every employee,DC=domain1,DC=local
It looks like user.Context.Name is null which is claimed to be the name of the domain.
Also, if the selected user is a local one, I should get the machine1\localuser1 value.
The SamAccountName contains only the user name, without the context (user1).
What is the best way to get that format from any UserPrincipal object?
If you need to do this for machine accounts, then your answer is the way to go.
But another way, strictly for Active Directory (in case it comes in handy some other time), is to look at the msDS-PrincipalName attribute, which you can get via the underlying DirectoryEntry object:
var de = (DirectoryEntry) user.GetUnderlyingObject();
de.RefreshCache(new [] { "msDS-PrincipalName" }); //retrieve it from AD
var domainUsername = de.Properties["msDS-PrincipalName"].Value;
Since it's a constructed attribute, it's not returned unless you specifically ask for it, which is what you use RefreshCache for.
The down-level logon format can be obtained via an NTAccount object. However, it requires some translation to convert the Principal's SID to an NTAccount:
string downLevelLogonName =
userPrincipal.Sid.Translate(typeof(System.Security.Principal.NTAccount)).ToString();
Using that code works in both case (domain or local computer users).

How can I access Active Directory data without exposing the password

I am just learning to access my Active Directory and need to figure out if it is possible to access the information without having the user account password in the code. This code works:
DirectoryEntry SharePointUpdate = new DirectoryEntry("LDAP://" + "comm2k8-dc3", "juser01", "password", AuthenticationTypes.Secure);
When I try this code:
String strPath = "LDAP:// DC=MYOrganization"
DirectoryEntry SharePointUpdate = new DirectoryEntry(strPath);
I get this error
"A referral was returned from the server.\r\n
Am I missing something??
I do not want to have the user name and password in the code. Is there anyway I can do this?
Is this code running in the context of either a domain service account or Network Service/Local System on a domain joined machine? If so, you can use that security context to access AD.
Your LDAP://DC=MYOrganization looks potentially strange. Is your domain really a single label domain called "MyOrganization", or does it have a legal FQDN? If it's called MyOrganization.net, for example, you would connect to LDAP://DC=MyOrganization,DC=net.

Validating active directory user using a user between two sub domains

I have the following scenario:
Domain company.com has two subdomains: a.company.com and b.company.com. The users are in both subdomains (mixed) but the technical user is only in a.company.com and has permissions on b.company.com as well as the domains are trusted.
When I try to generate a PrincipleContext as:
var oPrincipalContext = new PrincipalContext(ContextType.Domain, "b.company.com", null, ContextOptions.Negotiate | ContextOptions.Signing | ContextOptions.Sealing, "TechnicalUserName", "TechnicalUserPassword");
I get message that the user "TechnicalUserName" does not exists in "b.company.com". The message is okay but the user "TechnicalUserName" exist in "a.company.com" and has full privileges over "b.company.com"
The reason I have a technical user for creating PrincipleContext is because that context will be privileged to reset, change, and unlock other user active directory accounts.
What am I missing here?
How about passing "TechnicalUserName#a.company.com" instead of just "TechnicalUserName"?
According to this post PrincipalContext does not support cross forest lookups and you'll need to use a DirectoryEntry/DirectorySearcher instead.

Logon failure error when attempting UserPrincipal.FindByIdentity

I've been searching for solutions on this for a while now, but each thread a dead-end unfortunately.
I'm working on a C#/ASP.net web app that will only be used internally by our company. Anonymous access has been switched off both in IIS and my web.config file forcing IIS to use the windows authenticated user (Active Dir user).
My problem is that the following code works perfectly to get the required (or any) AD user:
using System.DirectoryServices.AccountManagement;
... other code ...
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain", "someADuser", "someADuserpassword");
UserPrincipal winuser = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "samaccountname");
"someADuser" used in the PrincipalContext above is the current logged in user through windows, thus authenticated and a valid AD user. Using the following code (with the exact same user still logged in) gives me a "Logon failure: unknown user name or bad password" error:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain");
UserPrincipal winuser = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "samaccountname");
It seems UserPrincipal.FindByIdentity doesn't use the logged in user's validated credentials for some reason if it's not specified in the PrincipalContext object - something I don't want to do.
Is it possible that the ctx aren't picking up the logged in Windows users for some reason, even if the necessary settings (i hope) is added to web.config :
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
And Anonymous access is completely disabled in IIS?
It seems UserPrincipal.FindByIdentity doesn't use the logged in user's validated credentials for some reason if it's not specified in the PrincipalContext object - something I don't want to do.
UserPrincipal.FindByIdentity doesn't care about the user's credentials at all. You're just performing a look up to see if the account exists. The reason you're getting an error is because the default user credentials (i.e. the identity that your web application is running as) doesn't have access to the directory, so it can't perform the look up. When you pass in the client's credentials to the PrincipalContext then the problem goes away because your client has a valid AD account with access to the directory.
You should investigate which identity is being used to run the application pool and make sure it has access to the directory.
Quite annoying as I though if anonymous access was turned off, the current principal would default to the user logged in to windows. It turns out it's not as indicated by #RogerN.
Using the following statement as mentioned by #TheKingDave, it basically impersonates the user logged in to windows and makes the current thread run on it's principal rather than the "ASP" (in my case) account.
Because all the users on our domain has query/read access to Active Directory, this shouldn't be a problem to get more detail on them, which is what I wanted in the first place.
The end code (was testing):
System.Web.HttpContext.Current.Request.LogonUserIdentity.Impersonate();
ctx = new PrincipalContext(ContextType.Domain, System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName);
UserPrincipal winuser = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "whicheveraccount");
Hope it helps some1 in future! thx! ;-)
I did a lot of search/research to resolve the issue, but nothing worked, at last, all what I did was to add # to the servername, container, username & password like below:
app.CreatePerOwinContext(() => new PrincipalContext(ContextType.Domain, #"abc.net", #"OU=Customers,DC=abc,DC=net", ContextOptions.SimpleBind, #"abcnet\authuser", #"!$%MyPassword"));
And it worked. doh!
So I found out how to pass the impersonated identity. I had a situation where, as an admin, I wanted to unlock a user account automatically. I had to get the user names into variables and pass them in to the function like this:
string accountname = #"domain\username";
string admin = "adminusername";
string domain = Environment.UserDomainName;
string password = "password";
string dc = "WIN2K8DC1"; // example host name of domain controller, could use IP
// This determines the domain automatically, no need to specify
// Use the constructor that takes the domain controller name or IP,
// admin user name, and password
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc, admin, password);
UserPrincipal winuser = UserPrincipal.FindByIdentity(ctx, accountname)
if (winuser != null)
{
WindowsImpersonationContext wic = Impersonation.doImpersonation(admin, domain, password); //class/function that does the logon of the user and returns the WIC
if (wic != null)
{
winuser.UnlockAccount();
}
}
Impersonation class functionality that can be used to return a WIC can be found on MSDN:
https://msdn.microsoft.com/en-us/library/w070t6ka(v=vs.110).aspx

Cant find users or groups with System.DirectoryServices.AccountManagement

I'm trying to integrate a system with Active Directory using the System.DirectoryServices.AccountManagement stuff. Our IT people have setup an AD box and my dev box is not part of this (or any) domain.
So far, I have 3 lines of code as a test:
var pc = new PrincipalContext(ContextType.Domain, "machine", "CN=Administrator,CN=Users,DC=domain,DC=com", "Password");
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "Administrator");
var gp = GroupPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "Admins");
Creating the PrincipalContext works as listed above, but if I try to use the domain name instead of the server name then I get an error : The server could not be contacted. So, I left this on the machine name.
When getting the user or group, I get an error : A local error has occurred.
For the user, I also tried this with the same result:
var user = UserPrincipal.FindByIdentity(pc, IdentityType.DistinguishedName, "cn=Administrator,ou=users,dc=domain,dc=com");
So, overall, I'm confused :(
Does anyone have any suggestions?
As a side note, I'd like to kick the programmer who thought that 'a local error has occurred' would be a useful error message!
Cheers
PS: I can use the SysInternals AD Explorer just fine from my machine and I can see the dn's I'm trying to use.
PPS: If I use machine.domain.com for the name when creating the PrincipalContext, it also fails to connect.
So this is one of those things that makes perfect sense AFTER you hack through to the solution. The problem was the Context was trying to use a Negotiated security context which is not configured. When I used SimpleBind it works just fine:
var pc = new PrincipalContext(ContextType.Domain, "machine", "DC=domain,DC=com", ContextOptions.SimpleBind, "CN=Administrator,CN=Users,DC=domain,DC=com", "Password");
Cheers
PS: A more useful error message would have saved me a days head scratching!
To do the search using the credentials of the current user, specify the domain as such:
new PrincipalContext(ContextType.Domain, "xyz.mycorp.com:3268", "DC=mycorp,DC=com");
From
When do I need a Domain Name and a Domain Container to create a PrincipalContext?

Categories

Resources