Getting the name of the current user (not the username) - c#

I've read a few posts about getting the name of the current user which use either of the following methods:
Environment.UserName;
System.Security.Principal.WindowsIdentity.GetCurrent().Name
This gets the username of teh current logged in user but what I'm wondering about is how to get the name of the user that is logged in?
(thus not the login but the name that is also saved and displayed when you lock the computer)

using System.DirectoryServices.AccountManagement;
UserPrincipal userPrincipal = UserPrincipal.Current;
String name = userPrincipal.DisplayName;
this code works for me

Related

Is the GUID Property of a UserPrinciple Object in Active Directory Unique and Non-spoofable?

We are using Windows active directory to log users in without a password. The way we are currently doing it like this:
using System.DirectoryServices.AccountManagement;
var context = new PrincipalContext(ContextType.Domain, System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName);
var result = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, Environment.UserName);
Then we have a stored SamAccountName in our database which we match against the returned result.SamAccountName
This is definitely not secure as users could have the same SamAccountName and log in using that.
We are exploring the use of the GUID which exists on the UserPrinciple (result.GUID). My question is, is this variable non-spoofable on the windows side? Can we match the GUID that exists on the UserPrincple object with a variable we store on our database? Is this secure? Does this property always exist on an AD UserPrinciple? If not, how would we securely authenticate a user through this Windows Active Directory Login?
"sAMAccountName" is unique in a domain.
But you can also use both "objectSID" and "objectGIUD" for this purpose,this fields remain unchanged.
Note That If an object is moved to another domain, the objectSID changes, but not the objectGUID.
Overall, the best choice is "objectGIUD"
according to https://social.technet.microsoft.com/Forums/windowsserver/en-US/a5c0a863-cad1-4df8-a194-cb58f24ab1e6/is-objectguid-unique-in-the-domainforest?forum=winserverDS

login control in asp.net how to keep information of current user?

login control in asp.net how to keep information of current user?
We use session for keep information of current user , but loin control or membership, how to keep current user data?
What is the method؟
MembershipUser currentUser = Membership.GetUser();
//Get Username of Currently logged in user
string username = currentUser.UserName;
//Get UserId of Currently logged in user
string UserId = currentUser.ProviderUserKey.ToString();
By using above code we can get currently logged user in login control
Here i written much code like from Membership i am getting currently logged in username no need to use MembershipUser event to get currently logged in user we have another simple way to get currently logged in username you just define like this in your page
string userName = Page.User.Identity.Name;
Source

Authenticate AD user with alternate UPN suffix

This question might match with question at link here indirectly.
I am working on website project based on Asp.Net 4.0 for corporate use.
There is a form in website which ask users for their AD username and password with domain name selected by default.
I know of ways to authenticate user by root domain name. But there are users whose domain names(UPN suffix) had been modified.
For e.g. the domain name is xyz.com. So user is authenticate by user#xyz.com and their passwords. But for some users their name is user#abc.com.
So how to validate such users with alternative UPN suffix other than root domain name?
After lot of search with hit and trial method, I was able to formulate solution for it with reason.
The following link User Principal Name in AD by Jorge de Almeida Pinto is worth mentioning here. Please get details for iUPN and eUPN from there.
I am explaining my problem statement again as scenario to make it more clear.
Scenario
There are only two users in AD in domain (domain.com) named as Anil and Alex.
iUPN for Anil is Anil#domain.com and that of Alex is Alex#domain.com (which is by default set by AD itself).
eUPN for Anil is been left blank (which means it will be Anil#domain.com, the default behavior of AD). But for Alex it is been set as Alex#dummy.com for any reason.
You can get idea for AD interaction from link Active Directory With C# which I found nicely written.
As a programmer, I want to write code for making these both users get logged in AD from code.
Issues
Anil#domain.com get logged in successfully.
Alex#dummy.com cannot get logged in.
Reason
I had not been able to found perfect root cause for it.
But my guess is that, AD itself put domain name after # (at the rate). Since domain name for Alex is dummy.com, so AD tries to found user with suffix as #dummy.com. And return result as no user found.
Solution
The solution was to dissect username and domain name.
Append root domain name (domain.com) as suffix to user (with separate domain name). And then try to login.
You can have questions that other unauthorized user can also get in by this way. No! Because passwords need to be matched.
Why it worked?
Because AD was able to found user with Alex#domain.com in domain.com.
Edit
The solution I provided work only for case when other user is having same sAMAccountName with same domain name.
But what if the sAMAccountName is itself set with as Alex#dummy.com. So true solution was to go as -
(1) Get sAMAccountName on basis of UPN.
/// <summary>
/// Get sAMAccountName for matching UserPrincipalName (UPN)
/// </summary>
/// <param name="domain">Domain name</param>
/// <param name="userName">Username</param>
/// <returns></returns>
protected string GetSamUsername(string domain, string userName)
{
string samName;
using (var pc = new PrincipalContext(ContextType.Domain, domain))
{
var user = UserPrincipal.FindByIdentity(pc, userName); // Search for this user
if (user == null) return null; // If user is not there, why go forward
samName = user.SamAccountName;
}
return samName;
}
(2) Now logging in by any user will work.
It also helps us to authenticate user existence in AD.
If your first attempt fails (using default domain name), display the form with the domain name option.
Or, provide a textbox for the domain name that is filled out ahead of time that your users can modify if necessary.
When authentication fails, be sure to show them a message indicating they need to pay attention to the domain name you have shown.
UPDATE:
private void AuthenticateUser(string loginID, string pwd) {
var search = new DirectorySearcher(m_rootDir);
if (-1 < loginID.IndexOf("#")) {
search.Filter = "(&(objectClass=user)(SAMAccountName=" + loginID + "))";
} else { // this is their Common Name
search.Filter = "(&(objectClass=user)(cn=" + loginID + "))"; // Get User By Full Name
}
// more code here
}

Get any users email

Currently I'm using to get the email for the current user.
string to;
MembershipUser username;
username = Membership.GetUser();
to = username.Email;
However when I try to pass a variable to get another users info I get an error.
Seems that Membership.Getuser() only works for the current user and not for another user.
Anyone have any suggestions on how to get the email of another user. Not the current user.
There is another method Membership.GetUser(string username) which gets a MembershipUser by username.
There is yet another one Membership.GetUser(object providerUserKey) which gets a user by whatever you've configured/coded to be providerUserKey.
Take your pick.

Changing AD User Account Property by using the UserPrincipal

I am trying to change the User Account Property in Active Directory by using the UserPrincipal.
I have read that we have to use the special account which has the write access to the Active Directory rather than the current log on user. So, I created the special class to impersonate by using the Special Account. But I am still having the
System.UnauthorizedAccessException: General access denied error
at user.Save(ctx); line.
System.Security.Principal.WindowsImpersonationContext newUser = clsImpersonate.ImpersonateUser("ADUser", "ADPassword");
if (newUser != null)
{
PrincipalContext ctx = blAD.GetAdminPrincipalContext();
UserPrincipal user = blAD.GetUserPrincipal(this.SAMAccount);
user.Enabled = false;
user.Save(ctx);
newUser.Undo();
}
How can I achieve this requirement? Thanks.
What permissions have been delegated to your special user? It needs to be able to write userAccountControl on the users in question.
I wouldn't impersonate the account first off! Gain access through by passing the values through ad first.
For the real issue, look at the error:
Get the principalContect.
Get the userprincipal.
Do what you want to do.
Save it, why are u using undo? Delete the Undo().
To access the Principle as another user, define your PrincipalContext with the credentials of the user and use that PrincipalContext when getting the UserPrincipal.
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain.tld", "ADUser", "ADPassword");
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, this.SAMAccount);
if (user != null)
{
user.Enabled = false;
user.Save();
}
If you are still getting the UnauthorizedAccess Exception, it is likely because the account you are specifying does not have access to write the userAccountControl attribute on the user object in Active Directory/LDS.

Categories