Get domain chosen by PrincipalContext - c#

I'm creating a custom login functionality for asp.net which validates against active directory. The user must be able to login with only his username or with his username and a domain (and a password in both cases).
Code:
AuthUser user = Authentication.getDomainAndUserName(givenUsername);
bool validAccount = false;
PrincipalContext network = null;
if (user.domain != "") network = new PrincipalContext(ContextType.Domain, user.domain);
else network = new PrincipalContext(ContextType.Domain);
if (UserPrincipal.FindByIdentity(network, IdentityType.SamAccountName, user.username) != null) {
validAccount = network.ValidateCredentials(givenUsername, givenPassword, ContextOptions.Negotiate);
}
The "AuthUser" contains the username and, if given, the domain. Now if a user didn't explicitly specify the domain the above still works fine.
So if you call
new PrincipalContext(ContextType.Domain);
It seems that the domain is set automatically.
In that case, how can i find out the domain it used?

You always can get the domain used from the user principal returned from UserPrincipal.FindByIdentity()

Related

Is there a way to get users full path in active directory in ASP.Net Core?

I need to validate a specific user's path in active diretory in order to let him to autenticate to my website. Is there a method that I can user to get the full path. I've lood into PrincipalSearch but I don't think that works for a specific user, it searches the full AD.
Here is what I have so far:
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, ip, container, user, pass);
UserPrincipal userAD = UserPrincipal.FindByIdentity(principalContext, username);
if (userAD != null)
{
if (principalContext.ValidateCredentials(username, password))
{
return true;
}
else
{
return false;
}
I wanted to get the full path in the Active Directory for the user that is used in the userAD variable. How should I do this? Any advice?
I used the method DistinguishedName in order to get the location of the user. The code is now something like this:
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, ip, container, user, pass);
UserPrincipal userAD = UserPrincipal.FindByIdentity(principalContext, username);
var path = userAD.DistinguishedName;
if (userAD != null)
{
if(path.Contains("blabla")){
if (principalContext.ValidateCredentials(username, password))
{
return true;
}
else
{
return false;
}
}
The DistinguishedName returns the full path of the user specified in userAD. Hope this is useful!

Get current active directory user and group c#

I'm trying to use the following code to get the local logged in user for my web application based on AD.
Here is what i'm trying;
string CurrentUser = WindowsIdentity.GetCurrent().Name;
PrincipalContext context = new PrincipalContext(ContextType.Domain, "isd");
UserPrincipal upUser = UserPrincipal.FindByIdentity(context, CurrentUser);
if(upUser != null)
{
}
However, it returns "IIS APPPOOL\DefaultAppPool" as the user and not isd\whoever
It's IIS7 and .net 4
Thanks

UserPrincipal.FindByIdentity error in Firefox

I have a method to retrieve a list of AD groups that a user belongs to. Here is the code:
public static List<GroupPrincipal> GetGroups(string userName)
{
List<GroupPrincipal> result = new List<GroupPrincipal>();
// establish domain context
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
UserPrincipal user = null;
// find your user
user = UserPrincipal.FindByIdentity(yourDomain, userName);
// if found - grab its groups
if (user != null)
{
PrincipalSearchResult<Principal> groups = user.GetGroups();
// iterate over all groups
foreach (Principal p in groups)
{
// make sure to add only group principals
if (p is GroupPrincipal)
{
result.Add((GroupPrincipal)p);
}
}
}
return result;
}
In both IE and Chrome, this can work fine, but in Firefox, it always gives me DirectoryServicesCOMException on the user = UserPrincipal.FindByIdentity(yourDomain, userName); I don't even have any idea what kind of exception that is. Can someone explain me what the error is and how to fix it? Thank you so much!
Change the call to look like this:
using (HostingEnvironment.Impersonate()){
user = UserPrincipal.FindByIdentity(yourDomain, userName);
}
You will need to make sure that your application pool has AD permissions. This will perform the underlying AD call using the credentials of the hosting environment (the web App Pool Identity) instead of the credentials of user, who may not have permissions to query the AD server.

c# Log In click event using authentication against Active Directory through LDAP

I am quite new to c# and LDAP, I'm doing this project so that I could learn about them in a more hands on approach.
What I'm trying to create is a Log in form that has a log in click event that would authenticate the username and password after the user enters them through the active directory using LDAP.
I have read Managing Directory Security Principals in the .NET Framework 3.5 to be able to understand this subject better and I have also gone through similar topics here this one dealing with the validation in itself (c# - Validate a username and password against Active Directory?) and this one authenticating a username (c# against Active Directory over LDAP)
From the first linked topic I had learned that the following code should do the trick in authenticating a username and password:
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://example.string.com/OU=Users, Dc=example, Dc= string, DC=com"))
{
bool isValid = pc.ValidateCredentials(User, Password);
}
So my approach to incorporate this to a click event was as follows:
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://example.string.com/OU=Users, Dc=example, Dc= string, DC=com"))
bool isValid = pc.ValidateCredentials(User, Password);
if(isValid)
{
Main m = new Main();
this.Close();
m.Show();
}
else
{
MessageBox.Show("Invalid Username and/or Password","Error!");
textBox1.Clear();
textBox2.Clear();
textBox1.Focus();
}
Which is giving me a bool error of Embedded Statement.
I tried the other approach I had read from the second post which was to use this code which authenticates only Username:
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://example.com/OU=Computers,OU=Users,dc=example,dc=com");
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "username");
bool userExists = (user != null);
But I found that I wont be able to authenticate a password using this method as UserPrincipal.FindByPassword does not exist.
I have also tried it this way but again .Password does not exist:
PrincipalContext pc = new PrincipalContext(ContextType.Domain,"LDAP://....");
UserPrincipal qbeUser = new UserPrincipal(pc);
qbeUser.EmployeeId = User;
//.Password does not exist
UserPrincipal qbePassword = new UserPrincipal(pc);
qbePassword.Password = Password;
// create your principal searcher passing in the QBE principal
PrincipalSearcher srchUser = new PrincipalSearcher(qbeUser);
PrincipalSearcher srchPass = new PrincipalSearcher(qbePassword);
// try to find that user and password
UserPrincipal founduser = srchUser.FindOne() as UserPrincipal;
UserPrincipal foundpass = srchPass.FindOne() as UserPrincipal;
if (founduser != null)
{
if (foundpass != null)
{
Main m = new Main();
this.Close();
m.Show();
}
else
{
MessageBox.Show("Password Not Valid.");
textBox2.Clear();
textBox2.Focus();
}
}
else
{
MessageBox.Show("Username Not Valid.");
textBox1.Clear();
textBox1.Focus();
}
Can someone kindly please instruct me as how one should correctly approach this.
Thank you in advance.
I have done this but not with PrincipalContext. Instead I have found many people struggling using that object.
My implemenatation was a winforms form and the submit button calls a method executing the 4 las lines of the code below.
I tested against this magnificent free to test LDAP server
var path = "LDAP://ldap.forumsys.com:389/dc=example,dc=com";
var user = $#"uid={username},dc=example,dc=com";
var pass = "password";
var directoryEntry = new DirectoryEntry(path, user, pass, AuthenticationTypes.None);
var searcher = new DirectorySearcher(directoryEntry);
searcher.PropertiesToLoad.Add("*");
var searchResult = searcher.FindOne();
I donĀ“t understand exactly what all of this lines does.
Important tips
On the path the "LDAP://" string should be on block mayus.
In the user, according to the test server you use "cn=username-admin" for validating admins, be sure to also set Authentication type to ServerBind.

UserPrincipal from Active Directory

I have problem with getting UserPrincipal from Active Directory. First of all I have used on my local environment (using not IIS but ASP.NET development Server):
User usr = new User();
usr.SoeId = Request.ServerVariables["LOGON_USER"];
usr.IP = Request.ServerVariables["REMOTE_ADDR"];
usr.FirstName = UserPrincipal.Current.GivenName;
usr.LastName = UserPrincipal.Current.Surname;
And it works fine. I got what I want. But when I install application on testing environment I got error "Object reference not set to an instance of an object". I have tried solution from here.
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
UserPrincipal up = UserPrincipal.FindByIdentity(pc, usr.SoeId);
return up.DisplayName;
// or return up.GivenName + " " + up.Surname;
}
But it does not work.
I use windows authentication. Impersonation is set to true. Please help me.
change the identity of your ApplicationPool to run using domain user.
in iis 6 right-click your application pool, go to Identity tab and set a domain user under which the pool will run.
in iis 7 right-click your application pool, select advance settings, under process model you'll find Identity, change it to use domain user.
you can also pass a domain user and pass to PrincipalContest Constructor
using (PrincipalContext context = new PrincipalContext(
ContextType.Domain,
"name of your domain",
"container of your domain",
"user#domain", //create a user in domain for context creation purpose.. this username will be constant.. you can keep it in app config
"password")){
UserPrincipal up = UserPrincipal.FindByIdentity(pc, usr.SoeId);
return up.DisplayName;
}
if your domain name is dom.com then your container would be something like DC=dom,DC=com and the user name should be given as user#dom.com or dom\user
Use this:
// find currently logged in user
UserPrincipal adUser = null;
using (HostingEnvironment.Impersonate())
{
var userContext = System.Web.HttpContext.Current.User.Identity;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["AllowedDomain"], null,
ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);
}
You must wrap any 'context' calls in HostingEnvironment.Impersonate

Categories

Resources