How to get currently Windows logged User Credentials? - c#

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.

Related

How to get ADAL to check username before using cached login credentials to logon user to application

I have an ASP.NET MVC application that uses Azure Active Directory for authentication. All works perfectly except for this scenario.
Launch application and login using user#domain.com, the user is authenticated and application home page is displayed
Close browser (Logoff not implemented)
Launch application again and click login as another user
Enter username as abc#domain.com - This user is fake and does not exist
Expected behavior: Some error saying the user does not exist or login failed
Application behavior: Logs in user#domain.com by default without checking the new username that's entered.
Note: portal.azure.com works the same way.
Question: Is there a way to change this behavior so that the username is validated or authenticated before the cached token is used.
thanks
This is by design.We do not go to AAD for authentication every time, cached credentials as used as the tokens / cookies the client has received during the initial login are good enough to get access to the resources.
There are two ways to achieve what you are looking for
1) Implement Sign out( feasible and optimum solution)
2) Implement a Auth filter and apply at a global level so for every request it has to validate the token and user name provide by user.
Hope it helps.

in an IIS web app, how do I get the windows user name? - not the process username

I have inherited an old asp.net web app. Part of the login process is intended to collect the windows username (not the process username). This used to work (years ago) but a new compile of the system returns the App Pool name / username instead of the windows username.
The username is collected before authentication by the website, originally using HttpContext.Current.User.Identity.Name
I have tried all the other options that have been suggested with no change in the results.
string loginName;
loginName = Environment.UserName;
loginName = HttpContext.Current.User.Identity.Name;
loginName = System.Windows.Forms.SystemInformation.UserName;
loginName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
loginName = System.DirectoryServices.AccountManagement.UserPrincipal.Current.SamAccountName;
loginName = System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName;
I tried these one at a time (not all together) and in the target environment only ever got the App Pool name or App Pool username.
I have tried every combination of Authentication in IIS, the only one that makes a difference is ASP.NET impersonation which changes from App Pool name to impersonation user name.
On my local PC, launched out of Visual Studio, they all work to return the windows logged in username.
I'm quite new to asp.net web apps, and I don't know what else to try.
You have stumbled on the answer. If you want the server to automatically know the windows user, that windows user's credentials need to be passed to the application. If you use the Kerberos or NTML authentication options (Windows Authentication) that set of credentials is passed automatically. Otherwise you need to prompt the user to enter credentials. You don't have to use impersonation, but you can programmatically impersonate the logged in user if your app pool user has sufficient access to the dc catalog. More on that here: https://learn.microsoft.com/en-us/previous-versions/msp-n-p/ff647405(v=pandp.10)#impersonating-the-original-caller-programmatically

get logon credentials in domain

I want to get network domain credentials of the user by my code.
string user = Environment.UserName;
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
I can get NAME with above samples, but I need password too. Is It possible to get password?
My purpose: I want to use the user's domain login credentials in my code, so the user do not have to login again to my windows app..., but i have to use login credentials for SoapHeader authentication...
Regards...
See this thread.
That's, what you have already:
You can get the current identity of the user under which the current
thread is running (not necessarily the logged in user) using
WindowsIdentity.GetCurrent(). Alternatively you can get the logged in
user name via the Environment.UserName property. It is not guaranteed
to be the user running the current process however.
Is it possible to retrieve the password? No, the password isn't stored in Windows:
There is no Windows API to get a user's password as passwords aren't
stored in Windows. Instead Windows stores a one-way hashed version.
Hope it helps!
EDIT: Documentation: Here are the associated docs to GetCurrent() and the returning value WindowsIdentity.

Get system logged in username in c# that also works in IIS

I thought its simple to get the logged in username, in fact, it works fine with most of the responses available on stack overflow but when I publish the website all method fails.
Can anybody please guide me to get the name of the logged in user from Windows with following condition.
I just need logged in user name so forget about AD when you write the response.
I cannot change to Windows authentication mode because user may be a guest user who is not part of company but still have access to my intranet website
it’s not possible to change the user browser setting as there are more than 6000 users
I cannot disable the anonymous authentication as I want everyone to be able to use the website
I have already tried following solution and all works fine when I run the website on debug mode but all fails to return the username when I publish the website on IIS so please help me with some new as solution
string _windowLogonUserName = System.Environment.UserName.ToString()
string _windowLogonUserName =
WindowsIdentity.GetCurrent().Name.Remove(0, _adDomainName.Length + 1)
string _windowLogonUserName =
System.Web.HttpContext.Current.User.Identity.Name.ToString();
System.Security.Principal.WindowsIdentity.GetCurrent().Name;
AppDomain appDomain = Thread.GetDomain();
appDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal windowsPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
Logger.Write("username principal" + windowsPrincipal.Identity.Name);
Request.ServerVariables["LOGON_USER"]
It sounds like you're publishing the site outside of the AD domain. if the server is not on the domain, it won't be able to authenticate (or even accept) Windows users. The basic answer is that you can't get it.
If the server is internal (on the domain) then you can enabled integrated windows auth in IIS. Here's a reference.

How to search Active Directory when dialed in remotely?

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.

Categories

Resources