Getting full names of users when using windows authentication.
One of the most common problems that we have faced with Windows Authentication is while displaying the users full name on screen after the user gets authenticated because there is no Property to get the name that comes with WindowsIdentity or there is no API in the Security.Principal namespace. The framework exposes Environment.UserName and WindowsIdentity.GetCurrent().Name to get username with domain. Instead of splitting the Name, we could have also used Environment.UserDomainName to pass the domain to the function that is getting us the full name of the user.
So here is example of how we can do that.
WindowsIdentity wi = WindowsIdentity.GetCurrent();
string[] split = wi.Name.Split(new char[] {'\\'});
string windowsLoginName = split[1];
string fullname = GetUserFullName(split[0], windowsLoginName);
The function to get the Full Name is below
public string GetUserFullName(string domain, string userName)
{
string userFullName = string.Empty;
try
{
DirectoryEntry userEntry = new DirectoryEntry("WinNT://" + domain + "/" + userName + ",User");
userFullName = (string)userEntry.Properties["fullname"].Value;
}
catch (Exception)
{
userFullName = string.Empty;
}
return userFullName;
}
No comments:
Post a Comment