How to search Active Directory when dialed in remotely? - c#

Is there a way to use a credential coming from the user's saved password list and use that instead of the local Windows credentials?
I need to look up a user's email address based on their Active Directory username to allow them to register for email updates via an intranet site. This seems easy enough if the user is actually logged into a machine directly that's part of the domain - I can use their identity name to search the AD based on their username:
using( DirectoryEntry root = new DirectoryEntry("LDAP://admachine.domain.local") )
{
using( DirectorySearcher searcher = new DirectorySearcher(root) )
{
// strip the domain from the username and find the user in AD
var username = Regex.Replace(Page.User.Identity.Name, #".*\\", string.Empty);
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = string.Format("(&(objectCategory=user)(objectClass=person)(sAMAccountName={0}))", username);
var foundUser = searcher.FindOne();
// error checking occurs here...
var email = foundUser.Properties["mail"][0].ToString();
// TODO: stuff with the email address
}
}
However, if working from a PC at home this doesn't work. Page.Identity.Name resolves to the name I'm logged onto my own PC (MyMachine\Dave), ignoring stored credentials I used to authenticate with my work domain (WorkDomain\dave.downs).
The DirectoryEntry picks up and uses the saved credential just fine, allowing me to actually bind to and search the AD, but I can't find a way of then using it as the var username, which will contain of my local machine username instead.
Is there a way to actually do what I'm trying to do, or am I just going about things the wrong way/hitting my head against a brick wall?

I assume you are using IIS. Disable Anonymous Access and enable windows authentication. That way anybody who is not in the domain will get a popup that allows them to specify their domain user and password. For users that are coming from a domain enabled server nothing changes. But that way you guarantee that the identity will always resolve to a valide domain user. So this should solve your "I am seeing a non-domain user" problem. Check Windows Authentication Provider for details.

If they are logged in via Windows Auth, you can use:
System.Security.Principal.WindowsIdentity.GetCurrent().User
which will give you the sid of the logged in user.
Disable anonymous access and integrated security in IIS, force them to log in via basic auth under https. This will give make sure the the current session is running under an authenticated domain user.

Related

How to get currently Windows logged User Credentials?

I am working on an ASP.NET Core 2.0 web app. It has it's login and own User interface.
I am trying to retrieve Windows logged users' credentials - like user name, email and password. On login in app, the logged in user's credentials are set as the User. So I need to retrieve windows logged in user's info before login process. I tried the following :
// If domain is example.com, DomainName gives EXAMPLECOM. Plus can't access Password
string evnName = Environment.UserDomainName + Environment.UserName;
In HomeController (after login) and Startup, I tried
// User is null
string userName = this.User.FindFirst(ClaimTypes.Name)?.Value;
I tried the above in a Service where login process is processed. Can't get from their too.
The main reason to retrieve this is to identify if the user has privileges for SMTP access or not, if so set SMTP.
Can anyone please help me know, how can I retrieve Windows Logged User's credentials somehow before Login process.
Thanks a lot.
You can get the current Windows user credentials by using the System.Net.CredentialCache.DefaultCredentials static property.
You won't be able to get the password as that would be a major security hole. You should be able to get everything else you want out of that, however.

Is there a way to have users that login their PC to have their authentication done using LDAP?

I want to create an MVC application that takes the credentials the user uses to login to thier PC and use those credentials to verify if the user lies on a particular domain using LDAP and if he does then get his details from active directory.
By using System.DirectoryServices
You can get user related info from local LDAP.
var ldapPath = "your-domain-ldap-path"
var directoryEntry = new DirectoryEntry(ldapPath, UserName, Password, AuthenticationTypes.Secure);
This should get you to the user.
System.Security.Principal.WindowsIdentity.GetCurrent()
System.Security.Principal.WindowsIdentity

How to use Windows User Login to authenticate with Webservice

I have a client-server application (both Windows, client is WPF, non-UWP) and i want to do authentication via active directory. My idea is to take the credentials (or a token) from the windows machine that the client is on and send that information to the server (via webservice, IIS, asp.net). the server then checks with ad if the credentials are valid and does authorization...
So the key points would be:
extract credentials/token from client-windows
send it via vebservice to server (that part should be simple)
validation on server against active directory
How can I achieve that?
If you want to check for a windows user authentication in a desktop application you can simpy use the
Environment.UserName
Variable, it provides the username of the current logged in user.
if you want to check if it is an active directory user you can call a function like this:
public bool UserExists(string username)
{
// create your domain context
using (PrincipalContext domain = new PrincipalContext(ContextType.Domain))
{
// find the user
UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);
return foundUser != null;
}
}
With your new request you can split the code above:
In the client you can get the AD username and domain using Environment variable, pass it to the server and check if the user exist using the UserExist() function

WPF application with Windows authentication

I have a simple wpf client (few text boxes) that uploads some data to a web service. And I want to use windows authentication to go with my application.
I am checking in OnStartup of App.xaml, whether or not the user is authenticated. My question is around what is the meaning of Thread.CurrentPrincipal.Identity.IsAuthenticated.
I don't want my application to be used from outside my network as it is connecting to a web service and uploads data. But my assumption is as long as you run this application from inside any windows network the above mentioned property will always return true?
So how do I find out if the application is being run from inside my network. I don't think checking domain name or role name is any different, because I can always setup a domain and name it whatever I want. I don't want to prompt user for username or password of any sort.
How do you check Identity of user against a particular AD (AD might not be publically available). Basically the application should only works from my local network or through VPN.
var context = new PrincipalContext(ContextType.Domain, "DOMAINNAME");
var result = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName);
If the result is null, then the user does not exists in the AD domain.
You can also user DirectorySearcher class to query AD based on a filter criteria. This is more useful only if you would like to retrieve additional details about the user like contact, email address etc.

Saving to Active Directory - Access Is Denied for Domain Admin

I'm working on a C# Web Application to allow read and write access to Active Directory user accounts.
I have got this working great on our main company AD- I can read accounts, get attributes, save details back to AD, enable/disable accounts etc. I'm using impersonation to do this, so just before it saves to AD it changes to using a different account (which belongs to Domain Admins), then reverts to the main app pool account after saving.
I've just been given the requirement to add user accounts through the app, but I'm not happy about testing this on the main AD, and I've therefore setup a VM with a test AD. I've got the app setup on that VM, and it reads from AD fine. I've setup the same user account that I impersonate on the live AD, and have added it to the domain admins group. However, when I try to save details to an existing user I get an "Access is Denied" error.
I know the impersonation is working as just before saving I output the result, and I tried changing the password and it failed with a different error.
I've asked our Network Administrator if he's setup anything special on the impersonation user for the live AD, but he says he hasn't, and they appear to be identical.
Does anyone know of anything else I might need to do other than add the impersonation user to the domain admins group? I've tried logging into the VM as the user, and have made a change to a user account through AD itself, so the user does seem to have the required level of access.
The following is the code I'm using to impersonate the user:
Impersonation imp = new Impersonation();
string impResult = "";
imp.ImpersonateDomainUser(out impResult, ConfigurationManager.AppSettings["ADAdminUserLogin"], user.Domain, ConfigurationManager.AppSettings["ADAdminUserPwd"]);
...
imp.Revert();
impResult returns the following:
Before impersonation: NT AUTHORITY\SYSTEM
After impersonation: TESTDOMAIN\user.manager.service
The code I'm using to save to AD is:
var entry = new DirectoryEntry();
var account = userName.Replace(domain, "");
var search = new DirectorySearcher(entry) { Filter = "(SAMAccountName=" + account + ")" };
search.PropertiesToLoad.Add(propertyName);
var result = search.FindOne();
if (result != null)
{
DirectoryEntry entryToUpdate = result.GetDirectoryEntry();
if (propertyValue == null || propertyValue.ToString().Length == 0)
entryToUpdate.Properties[propertyName].Clear();
else
entryToUpdate.Properties[propertyName].Value = propertyValue;
entryToUpdate.CommitChanges();
entryToUpdate.Close();
entryToUpdate.Dispose();
}
Any advice would be much appreciated.
This issue was down to User Access Control settings on the Virtual Machine.
Once I disabled User Access Control through the control panel, I was then able to save users to Active Directory. Its possible that running the browser as administrator may have also worked, though I didn't try this.

Categories

Resources