SimpleBind Authentication against Active Directory - c#

I'm trying to authenticate login credentials against Active Directory (AD DS) using the following code:
using (var context = new PrincipalContext(ContextType.Domain, ipAddress))
{
Console.WriteLine("Connected to {0}:", context.ConnectedServer);
context.ValidateCredentials(username, password);
}
Where ipAddress is the address of the primary domain controller. However this gives the following error when attempting to read context.ConnectedServer:
System.DirectoryServices.DirectoryServicesCOMException (0x8007052E):
The username or password is incorrect.
In addition to this issue I have the following constraints:
The production environment may or may not be on the domain.
The clients do not want to enter any privileged credentials to query the directory.
Due to this second constraint I have tried to execute a SimpleBind, but without much luck:
using (var context = new PrincipalContext(ContextType.Domain,
ipAddress,
null,
ContextOptions.SimpleBind,
usernameToValidate,
password))
Based on these constraints, how can I authenticate against Active Directory?

I was able to authenticate using the following code:
using (var context = new PrincipalContext(ContextType.Domain, ipAddress))
{
// NOTE! Username must be of the format domain\username
return context.ValidateCredentials("domain\someuser", password, ContextOptions.SimpleBind);
}
The key part was to prefix the username with the short domain name. Once I did that, and specified SimpleBind in the call to ValidateCredentials instead of in the context constructor, it worked fine.

Related

What PrincipalContext does UserPrincipal.GetGroups() use if not specified?

In the case that I'm getting groups for a UserPrincipal identity (in an Active Directory role provider), and I use the UserPrincipal.GetGroups() function that does not require a PrincipalContext as parameter, what does it default to using for the PrincipalContext? I ask as in troubleshooting an issue, I'm seeing seeing it connect to a different AD server that is not the connected server for my PrincipalContext. Some code as an example:
using ( PrincipalContext context = new PrincipalContext( ContextType.Domain, "domain", null, ContextOptions.Negotiate ) )
{
UserPrincipal identity = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, username );
if (identity != null)
{
var groupList = identity.GetGroups();
}
}
If I output context.ConnectedServer I get a valid active server. However, identity.GetGroups() appears to connect to a different server (in my case, it's throwing a System.DirectoryServices.ActiveDirectory.ActiveDirectoryServerDownException because it's connecting to an old server). If I instead use identity.GetGroups(context), the groups are correctly returned. Why does calling GetGroups without a PrincipalContext cause it to default to connecting to a different server?

Validate users of Remote Active Directory in C#

I try to authenticate users belonging to remote ActiveDirectory from my machine, which is not the same domain as the current machine or user domain. There will be no trust between my machine and remote ActiveDirectory machine.
Initial Try
I tried to authenticate a user(Input: sAMAccountName, machine's ipaddress, machine's domain username("Administrator") and machine's password(***). Able to get result that the user with 'sAMAccountName' do exist in ActiveDirectory.
My Requirement:
Imagine that already a user("qwerty") is created in ActiveDirectory
From my local machine, I will have the following information,
a. Remote ActiveDirectory ipaddress
b. Remote ActiveDirectory machine's username and password.
c. Username and password of User "qwerty"
I need to check whether User "qwerty" is present in remote ActiveDirectory's users list and validate whether the password entered is same in ActiveDirectory's Users list
Code I tried:
DirectoryEntry entry = new DirectoryEntry("LDAP://ipaddress/DC=dinesh,DC=com", name, password);
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "(sAMAccountName=" + name + ")";
try
{
SearchResult adsSearchResult = adsSearcher.FindOne();
isValid = true;
adsEntry.Close();
}
catch (Exception ex)
{
adsEntry.Close();
}
Do I need to create a trust between local machine and remote ActiveDirectory machine before validating Users in a remote ActiveDirectory? If yes please tell how it can be done;
After creating trust, how can I validate Users?
===========================================================================
I am able to use the solution suggested by Rainer, but with a new problem. When I create a new user via C# code from a different machine, then some properties do not set properly.
Does this need to be set compulsorily while creating user?
First some basics (independent of this question)
Authentication
The system checks if Bob is really Bob. In an Active Directory environment, this is usually done with a domain login from the workstation, Bob enters his username and password, and he gets a Kerberos ticket. Later, if he wants to access e.g. a file share on a remote fileserver, he does not need to login anymore, and can access the files without entering username/password.
Authorization
The system checks which resources Bob is allowed to access. Usually Bob is in domain groups, and a group is in the ACL (access control list) of the resource.
If there are multiple trusting domains, Bob needs to login in one domain, and can access resources in all other domains.
This is one of the main reasons using Active Directory: single sign on
Checking if user / password is valid
If you have a username and password and want to check if the password is valid, you have to do a login to the domain. There is no way of just “checking if the password is correct”.
Login means: if there is a security policy “lock account if more than 3 invalid logins”, the account will be locked out checking with wrong password, even if you “only want to check the user+password”.
Using .NET Directory Service functions
I assume here that the process is either run by a human account as a normal program, or the program is a Windows service or a scheduled task which runs under a domain “technical user” account. In this case, you do not need to provide credentials for using the AD functions. If accessing other trusting AD domains, this is also true.
If you want to login to a “foreign domain”, and there is no trust, you need to provide a username+password (as in your code).
"Manually" authenticating a user
Normally, this should not be needed. Example: ASP.NET intranet usage. The user access a web application on the current domain or trusting domain, the authentication is done “in the background” by browser and IIS (if integrated Windows authentication is on). So you never need to handle user passwords in the application.
I don’t see many use cases where a password is handled by code.
One may that your program is a helper tool for storing emergency user accounts/passwords. And you want to check periodically if these accounts are valid.
This is a simple way to check:
using System.DirectoryServices.AccountManagement;
...
PrincipalContext principalContext =
new PrincipalContext(ContextType.Domain, "192.168.1.1");
bool userValid = principalContext.ValidateCredentials(name, password);
One can also use the older, raw ADSI functions:
using System.DirectoryServices;
....
bool userOk = false;
string realName = string.Empty;
using (DirectoryEntry directoryEntry =
new DirectoryEntry"LDAP://192.168.1.1/DC=ad,DC=local", name, password))
{
using (DirectorySearcher searcher = new DirectorySearcher(directoryEntry))
{
searcher.Filter = "(samaccountname=" + name + ")";
searcher.PropertiesToLoad.Add("displayname");
SearchResult adsSearchResult = searcher.FindOne();
if (adsSearchResult != null)
{
if (adsSearchResult.Properties["displayname"].Count == 1)
{
realName = (string)adsSearchResult.Properties["displayname"][0];
}
userOk = true;
}
}
}
If your real requirement is actually a validity check of user+password, you can do it in one of these ways.
However, if it is a "normal application", which just wants to check if the entered credentials are valid, you should rethink your logic. In this case, you better should rely on the single sign on capabilities of AD.
If there are further questions, please comment.
b. Remote ActiveDirectory machine's username and password.
This sounds a bit unclear. I assume you mean "a username and corresponding password in the remote domain".
There is also the concept of a machine account, which is the hostname appended with $. But that's another topic.
Creating new user
Option 1
using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://192.168.1.1/CN=Users,DC=ad,DC=local",
name, password))
{
using (DirectoryEntry newUser = directoryEntry.Children.Add("CN=CharlesBarker", "user"))
{
newUser.Properties["sAMAccountName"].Value = "CharlesBarker";
newUser.Properties["givenName"].Value = "Charles";
newUser.Properties["sn"].Value = "Barker";
newUser.Properties["displayName"].Value = "CharlesBarker";
newUser.Properties["userPrincipalName"].Value = "CharlesBarker";
newUser.CommitChanges();
}
}
Option 2
using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "192.168.1.1",
"CN=Users,DC=ad,DC=local", name, password))
{
using (UserPrincipal userPrincipal = new UserPrincipal(principalContext))
{
userPrincipal.Name = "CharlesBarker";
userPrincipal.SamAccountName = "CharlesBarker";
userPrincipal.GivenName = "Charles";
userPrincipal.Surname = "Barker";
userPrincipal.DisplayName = "CharlesBarker";
userPrincipal.UserPrincipalName = "CharlesBarker";
userPrincipal.Save();
}
}
I leave as an exercise to you to find out which attribute goes into which User dialog entry field :-)

Unable to validate credentials using LDAP

I am new to LDAP and wanted to connect to a LDAP server using .Net to validate the user credentials. The following code returns an error:
The LDAP server is unavailable
But the validation works fine in Java code. Kindly let me know where I have gone wrong.
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://192.168.65.201:389/DC=be,DC=ndl,DC=CompanyName,DC=com"))
{
bool a= pc.ValidateCredentials("myname#CompanyName.com","password");
}
First of all - PrincipalContext only works against Active Directory, not against any other LDAP server.
Secondly: you're specifying invalid parameters for the constructor. Check out the MSDN docs on what constructors are available for PrincipalContext.
You can define just a ContextType parameter, in which case the PrincipalContext is constructed against the current domain you're connected to:
var ctx = new PrincipalContext(ContextType.Domain);
Or you can use a constructor with a second string parameter which signifies the domain name of your domain (only the domain name - NOT a complete LDAP path!):
var ctx = new PrincipalContext(ContextType.Domain, "CompanyName.com");
Then you're connected to that specific domain, at the root level.
Or thirdly, you can specify a third parameter which defines the container in that domain to connect to:
var ctx = new PrincipalContext(ContextType.Domain, "CompanyName.com",
"CN=Users,DC=be,DC=ndl,DC=CompanyName,DC=com");
So you'll need to find the appropriate constructor and supply the correct parameters to get this to work - if you're using Active Directory.

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

Active Directory, enumerating user's groups, COM exception

while enumerating current user's groups through AD .NET API I sometimes get
COMException: Unknown error (0x80005000)
Here's my code :
var userName = Environment.UserName;
var context = new PrincipalContext(ContextType.Domain);
var user = UserPrincipal.FindByIdentity(context, userName);
foreach (var userGroup in user.GetGroups())
{
Console.WriteLine(userGroup.Name);
}
What's the problem? I thought every user can retrieve list of HIS groups?It seems to be strange behavior, sometimes It can be reproduced like this : when running on 'userA' PC, It crashes, but it is enumerating OTHER 'userB' groups successfully (under 'userA')!
Try using
var context = new PrincipalContext(ContextType.Domain, "yourcompany.com", "DC=yourcompany,DC=com", ContextOptions.Negotiate);
With the ContextOption set to Negotioate the client is authenticated by using either Kerberos or NTLM so even if the user name and password are not provided the account management API binds to the object by using the security context of the calling thread.
I had the same problem, I solved it by supplying the domain name when creating the PrincipalContext:
var domain = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);
var user = UserPrincipal.FindByIdentity(domain, Environment.UserName);
0x80005000 = E_ADS_BAD_PATHNAME so you supply an invalid adspath somewhere, maybe you must add LDAP:// prefix or opposit are doing this twice? Set a breakpoint and inspect value...
EDIT:
AdsPath should be a value like "LDAP://CN=Administator,CN=Users,DC=contoso,DC=com", you seem to have a misformed path.

Categories

Resources