Get fullname from Active Directory on C# - c#

I have a problem about getting user's firstname and surname (fullname) from Active Directory. The code is below.
No problem with runing the project on my local. I can take data whatever I want. After publishing the project to remote server, it don't allow me to get firstname and surname (fullname), it just allows to get domain name and username. How can I fix it?
private string GetNameSurname()
{
string[] retVal;
//Pull the username out of the domain\user string.
retVal = Page.User.Identity.Name.Split(new string[] { #"\"},StringSplitOptions.RemoveEmptyEntries);
DirectoryEntry userEntry = new DirectoryEntry("WinNT://" + retVal[0] + "/" + retVal[1]);
string namesurname = (string)userEntry.Properties["fullname"].Value;
//return retVal[1];
//retVal[1] gives username.
//retVal[0] gives domain name
return namesurname;
}

Are you running the code to test for the same user?
Are you testing against AD in dev, Windows local accounts have a Full Name field (optional) but in AD the fields are named differently. Also, are you talking to the same version of AD.
According to the MSDN article there is no field called Full Name, only First Name and Surname and Display Name.

I think your problem is about credentials. Try to add an administrator username and password when conecting to active directory.

Related

Converting username to SID in C#

I'm trying to use this code to convert a Windows username (in the classic .\username form) to a SID object:
NTAccount account = new NTAccount(".\\MyUser");
SecurityIdentifier sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
However, I keep getting the following exception when executing the last instruction:
System.Security.Principal.IdentityNotMappedException: 'Some or all
identity references could not be translated.'
What am I doing wrong?
Answering my own question after some trial and error:
The code is correct, but the Translate function doesn't seem to support the shorthand . to indicate the account is local and not in a domain. So in case you have a username that starts with .\ you need to replace the dot with the machine name. The following code works correctly:
public static SecurityIdentifier usernameToSid(string user)
{
if (user.StartsWith(#".\"))
{
user = user.Replace(#".\", Environment.MachineName + #"\");
}
NTAccount account = new NTAccount(user);
return (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
}

WindowsIdentity: Exception: System.Security.SecurityException: The user name or password is incorrect

On Windows Server 2012 R2 we want to get the Security Groups of an user from the Active Directory by C#-code. The application is an ASP.NET MVC5-project and is hosted by an IIS.
At first, we query the user account from the Active Directory by UserPrincipal.FindByIdentity(...). That works fine. At next, we use the WindowsIdentity class to query the Security Groups from the active directory. We use the class WindowsIdentity because the response is very fast.
Here is the code:
var lDomain = "MyDomain";
var lSamAccountName = "Simon";
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, lDomain))
{
// Get User Account from Active Directory
using (UserPrincipal lUserPrincipal = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, lSamAccountName))
{
var lUpn = lUserPrincipal.UserPrincipalName; // get UPN
// get Security Groups of the user
using (WindowsIdentity lWindowsIdentity = new WindowsIdentity(lUpn)) // Exception: System.Security.SecurityException: The user name or password is incorrect
{
var lGroups = lWindowsIdentity.Groups;
}
}
}
The problem: When instanciating the WindowsIdentity class (and passing the UPN) then an exception occurs:
“Upn: 'simon#MyDomain' Exception: System.Security.SecurityException: The user name or password is incorrect.
at System.Security.Principal.WindowsIdentity.KerbS4ULogon(String upn, SafeAccessTokenHandle& safeTokenHandle)
at System.Security.Principal.WindowsIdentity..ctor(String sUserPrincipalName, String type)
at System.Security.Principal.WindowsIdentity..ctor(String sUserPrincipalName)
at ...
This is curious because the query with UserPrincipal.FindByIdentity(...) was successful. Some accounts are working. Some accounts are not working. I cannot find a difference between the working und not working accounts.
Question: Who knows what I am doing wrong?
Additional Notes:
The Applicationpool Identity is: LocalSystem
In the Web.config, there is the following entry: <identity impersonate="false" />
When I query the groups by the following alternative, then no exception occurs and the result is satisfying. That´s curious:
var lResult = new List<SecurityIdentifier>();
DirectorySearcher lDirectorySearcher = new DirectorySearcher();
lDirectorySearcher.Filter = string.Format(CultureInfo.InvariantCulture, "(&(objectClass=user)(distinguishedName={0}))", lUserPrincipal.DistinguishedName); // for the object lUserPrincipal, look # code above
lDirectorySearcher.SearchScope = SearchScope.Subtree;
SearchResult lSearchResult = lDirectorySearcher.FindOne();
DirectoryEntry lDirectoryEntry = lSearchResult.GetDirectoryEntry();
lDirectoryEntry.RefreshCache(new string[] { "tokenGroups" });
// get groups
for (int i = 0; i < lDirectoryEntry.Properties["tokenGroups"].Count; i++)
{
SecurityIdentifier lSid = new SecurityIdentifier((byte[])lDirectoryEntry.Properties["tokenGroups"][i], 0);
lResult.Add(lSid);
// Translate into NTAccount to get Domain and SAMAccountname etc...
[...]
}
I really do not know if this helps, but somewhere I found this:
If IIS is set to allow anonymous access you can use the userPrincipleName format (username#domain).
If anonymouse access is NOT enabled in IIS you need to use the username in the form domain\username.
Seems weird though that for some accounts the UPN works and for others it does not..
Resolution 1:
Use ADSI Edit (via MMC.exe) to manually populate the userPrincipalName attribute of the desired Windows Service Account.
The format of a userPrincipalName is
<username>#<fully_qualified_domain_name>
For example, for the example log lines above, the expected UPN value should be
goodadmin#example.com
Allow a few minutes for Active Directory replication to complete before attempting to use the service account credentials.
Resolution 2:
Ensure the Active Directory Service Account information has the necessary permissions on the local BEMS host as Local Administrator and Logon As A Service.
Ensure the Active Directory Service Account information entered is actually valid. For example, ensure the password is entered correctly and that the account is not locked out in Active Directory.
Ensure the Active Directory Service Account information has the necessary Active Directory Group Permissions.
RTCUniversalReadOnlyAdmins
Here you can find how to get groups base on the UserPrincipal
How to create WindowsIdentity/WindowsPrincipal from username in DOMAIN\user format
// find all groups the user is member of (the check is recursive).
// Guid != null check is intended to remove all built-in objects that are not really AD gorups.
// the Sid.Translate method gets the DOMAIN\Group name format.
var userIsMemberOf = p.GetAuthorizationGroups().Where(o => o.Guid != null).Select(o => o.Sid.Translate(typeof(NTAccount)).ToString());
// use a HashSet to find the group the user is member of.
var groups = new HashSet<string>(userIsMemberOf), StringComparer.OrdinalIgnoreCase);
groups.IntersectWith(groupNames);

How to use C# to create User with Alias in Google Admin SDK Directory?

So I have some code that works, mostly. I am able to create a user with the Google Admin SDK Directory API but the alias that I specify does not get created for the user. What am I doing wrong? Is it a separate operation(like a patchrequest?) to create an alias for an account? I'm not getting any errors, the alias simply is not there after I've created the account.
UsersResource.InsertRequest user = this.service.Users.Insert(new User
{
PrimaryEmail = this.pid + "#" + Domain,
Name = new UserName
{
GivenName = this.usedfname,
FamilyName = this.lname,
FullName = this.usedfullname,
},
Aliases = new List<string>()
{
this.usedfname + "." + this.lname + "#" + Domain,
},
Password = this.password,
});
user.Execute();
FYI, this is a part of a class. An example of creating an alias in c# would be very helpful but I can't seem to find an example anywhere.
You can't create a user and aliases in one API call. You need to create the user and then call users.aliases.insert()

Current user name if account name has changed

I try to get the name of the current logged in user in c# - not the account name which I could find easily in Environment.UserName.
I would like to enumerate the folders on MyComputer like explorer does it. How could I do that or is there another way to get the correct name of the user?
Thanks in advance.
Try using:
System.Security.Principal.WindowsIdentity.GetCurrent().Name This should return the account of the currently logged in user, and their name.
If that doesn't work after a username change, another method would be to get the current user's SID, then look up a username matching that SID.
using System.Security.Principal;
string sid = WindowsIdentity.GetCurrent().Owner.ToString();
return new SecurityIdentifier(sid).Translate(typeof(NTAccount)).ToString();
Failing this, take the SID and try and find a matching user either via WMI or via the registry. Instructions on how to do this manually are here: http://pcsupport.about.com/od/registry/ht/find-user-security-identifier.htm
If you can manually confirm that either of those methods return the NEW username, then just implement that in code, with either WMI calls or registry access.
Use it ,
string windowLoging = WindowsIdentity.GetCurrent().Name;
or
string windowsLogin = Page.User.Identity.Name;
or
string windowsLogin = Environment.GetEnvironmentVariable("USERNAME");
#damienc88
Your link leads me to the solution:
SelectQuery query = new SelectQuery("Win32_UserAccount", string.Format("Domain='{0}'", Environment.MachineName));
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject mObject in searcher.Get())
{
Console.WriteLine((string)mObject["Name"] + "\t" + (string)mObject["FullName"]);
}
"FullName" is the property which I've searched for. Thanks a lot. – Harald Pitro

Check Password Reset on Active Directory Server

I need to reset windows password of any user through my .Net application. I am using the user's username to get its Directory Entry from AD server. I got these two different methods for changing password :
entry.Invoke("ChangePassword", oldPass, newPass);
&
entry.Invoke("SetPassword", "pass#123");
But I am getting the following error when am trying these methods on live AD server :
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
I have 2 AD servers. One of them is live and another is for testing purpose. I just want to check if my code is working or not. Since, access is denied on live server I can not change and check later my own password through code.
And if I am using the test AD server to change password, I don't know how to check whether the pasword is changed or not.
Kindly give any suggestions to check if my code is working properly or not.
Thanks in advance.
I think you're not getting a proper context setup before you call the invoke. Here's what I use for something similar. You'll need to set your own variables:
I'm using System.DirectoryServices.AccountManagement to get the functions.
//Domain related info
string _DCToUse = "myserver.domain.local";
string _ADConDomain = "DC=domain,DC=local";
string _AdDomain = "domain";
string _ADAdminUser = "administrator";
string _ADAdminPass = "password";
//User specific
string _UserName = "jsmith";
string _CurrentPass = "oldPass";
string _NewPass = "newPass";
PrincipalContext principalContext =
new PrincipalContext(ContextType.Domain, _DCToUse,
_ADConDomain, _ADDomain+#"\"+_ADAdminUser, _ADAdminPass);
UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, _UserName);
if (user == null)
{
string ADErrorMsg = "Couldn't find user, check your spelling.";
return Changed;
}
user.ChangePassword(oldPass, newPass);
user.Save();

Categories