I need to show only the name of a user from Active Directory, I am using
lbl_Login.Text = User.Identity.Name; //the result is domain\username
This shows the users name but not the real name of the user, I've checked other questions and answers related here but I've not gotten the solution.
Is there any property just as "User.Identity.Name" to get only the name of the user?
You want name of a user from active directory. Try code like this:
string name ="";
using (var context = new PrincipalContext(ContextType.Domain))
{
var usr = UserPrincipal.FindByIdentity(context, User.Identity.Name);
if (usr != null)
name = usr.DisplayName;
}
or this from social.msdn.microsoft.com:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.Current;
string displayName = user.DisplayName;
or may be it:
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;
The System.DirectoryServices.AccountManagement namespace provides uniform access and manipulation of user, computer, and group security principals across the multiple principal stores: Active Directory Domain Services (AD DS), Active Directory Lightweight Directory Services (AD LDS), and Machine SAM (MSAM).
using System.DirectoryServices.AccountManagement;
string fullName = null;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal user = UserPrincipal.FindByIdentity(context, User.Identity.Name))
{
if (user != null)
{
fullName = user.DisplayName;
lbl_Login.Text = fullName;
}
}
}
Related
I'm writing a script to get a list of the current user's AD Groups and creates a .txt file to a Path.
I've had a look around and it seems like I should be using these references:
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
I'm also using this:
UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, "<Domain>"), IdentityType.SamAccountName, "<UserName>");
foreach (GroupPrincipal group in user.GetGroups())
{
Console.Out.WriteLine(group);
}
But this doesn't quite list all the groups that the user should be in.
Is there something I'm missing?
I use this block of code to get the user groups:
String domainName = #"<your domain>";
String username = domainName + #"\<your username>";
PrincipalContext thisDomain = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(thisDomain, username);
PrincipalSearchResult<Principal> userGroups = userPrincipal.GetAuthorizationGroups();
foreach (Principal principal in userGroups.OfType<GroupPrincipal>())
{
Debug.WriteLine(principal.Name);
}
As far as I can tell, it lists all the groups the user is a member of by comparison to what is held in Active Directory and looking at the user object in the MMC snap in
I am trying to get the manager's account for a user account in active directory.
Here's the code I have..
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
DirectoryContext directoryContext = new DirectoryContext(DirectoryContextType.Domain, "MyDomain");
Domain domain = Domain.GetDomain(directoryContext);
// Find MY directory Entry
DirectorySearcher search = new DirectorySearcher(domain.GetDirectoryEntry())
{
Filter = String.Format("(SAMAccountName={0})", "<my user id>")
};
search.PropertiesToLoad.Add("displayName");
search.PropertiesToLoad.Add("mail");
search.PropertiesToLoad.Add("manager");
DirectoryEntry userAccount = search.FindOne()?.GetDirectoryEntry();
As you can see, there's a property called manager that is requested and comes back as
CN=Manager Name,OU=Employee,OU=United Kingdom, OU=CompantUsers, DC=MyDomain, DC=xxx,DC=zzzzz
The CN=Manager Name is the full name, not the LoginID/SAMAccountName (as used when I searched for MY AD entry ... so how can I now find the AD entry for my manager
Ahhh ... When you know the right question to ask then Google knows the answer ... I did not know that the CN..... string was known as a distinguishedName
if (userAccount.Properties["manager"].Value != null)
{
DirectorySearcher search2 = new DirectorySearcher(domain.GetDirectoryEntry())
{
Filter = string.Format("(distinguishedName={0})", userAccount.Properties["manager"].Value)
};
search2.PropertiesToLoad.Add("displayName");
search2.PropertiesToLoad.Add("mail");
search2.PropertiesToLoad.Add("manager");
DirectoryEntry mgrAcc = search2.FindOne()?.GetDirectoryEntry();
}
I'm writing a web service that checks if the user exists in Active Directory and if the user account is enabled. Once it checks that, I then go ahead validate their user account. Once they successfully enter username and password, I would like to get the GUID or NativeGuid for the person I'm authenticating. I would like to use GUID or NativeGUID to build a relationship inside SQL Server database.
Here's the approach I'm taking:
public string isAuthenticated (string serverName, string userName, string pwd)
{
string _serverName, _userName, _pwd;
_serverName = serverName;
_userName = userName;
_pwd = pwd;
string message;
if (DoesUserExist (_userName) == true)
{
if (isActive(userName) == true)
{
try
{
DirectoryEntry entry = new DirectoryEntry(_serverName, _userName, _pwd);
object nativeObject = entry.NativeObject;
//issue is here
string GUID = entry.Guid.ToString();
string GUIDID = entry.NativeGuid;
//end of issue
message = "Successfully authenticated";
}
catch(DirectoryServicesCOMException ex)
{
message = ex.Message;
}
}
else
{
message = "Account is disabled";
}
}
else
{
message = "There's an issue with your account.";
}
return message;
}
When I try to get the GUID or NativeGUID it's returning me the same ID every single time for different users.
Is there a different approach I can take to get a UNIQUE ID for different objects in Active Directory?
Thanks
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, _userName);
if(user != null)
{
// get the GUID
var objectGuid = user.Guid;
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD! I don't have an AD lying around right now to test - but I hope this will indeed give you the user object's objectGuid property value.
The following code will check for the user when the user select a Domain account by selecting a value from the txtboxDomain.Text
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, txtboxDomain.Text))
{
// validate the credentials
bool isValid = pc.ValidateCredentials(txtboxUsername.Text, txtboxPassword.Text);
if (isValid == true)
{
lblLogin.Text = "Valid User Name and/or Password";
Session["Person"] = txtboxUsername.Text;
Session.Timeout = 1;
Response.Redirect("default.htm");
}
else
{
lblLogin.Text = "Invalid User Name and/or Password";
}
}
So, how do I code so that if the user only want to use the local system account? (Suppose that the local system name is WIN2008R2_LOCAL?
Do I write the code as using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "WIN2008R2_LOCAL"))
(I tried the above code but it does not work. So wondering how should I code then.)
PrincipalContext pc = new PrincipalContext(ContextType.Machine, null);
I'm using the System.DirectoryServices.AccountManagement namespace to find domain users and their corresponding AD security groups. This works well.
I'm also using that namespace to query the local security groups on a remote server. I am able to find a security group and then list the users of that group no problem.
What I'm having issues with is displaying which LOCAL groups a DOMAIN user belongs to:
PrincipalContext localmachine = new PrincipalContext(ContextType.Machine, "ServerName");
PrincipalContext domain = new PrincipalContext(ContextType.Domain);
// find the user using the domain context (Works fine)
UserPrincipal user = UserPrincipal.FindByIdentity(domain, userName);
// if found - grab its groups
if (user != null)
{
// The get groups method is the only method that would accept a new context
PrincipalSearchResult<Principal> groups = user.GetGroups(localMachine);
// no groups are returned .... removed rest of code
}
I'm attempting to use the GetGroups method passing in the localMachine PrincipalContext but no groups are returned.
The users exists only in the Domain AD. There is not an entry for this user in the local users on the localMachine. The domain users are added to local security groups.
Any ideas? I'd like to be able to pull a list of all local groups this domain user belongs to and then see if a certain groups exists in that list. The only option that is working now is for me to search certain groups on the system and see if the domain user belongs to that group.
The following code will return the local groups that a domain user is member of:
PrincipalContext domain = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(domain, userName);
foreach (GroupPrincipal group in user.GetAuthorizationGroups())
{
if (group.Context.ConnectedServer == serverName)
Console.Out.WriteLine("{0}\\{1}", group.Context.Name, group.SamAccountName);
}
I know my answer is late, but this worked for me (after I tried all sorts of permutations):
private static IList<string> GetUserLocalGroups(string userAccountName, string computerName, string domainName)
{
List<string> groups = new List<string>();
// We have to deal with a local computer
DirectoryEntry root = new DirectoryEntry(String.Format("WinNT://{0},Computer", computerName), null, null, AuthenticationTypes.Secure);
foreach (DirectoryEntry groupDirectoryEntry in root.Children)
{
if (groupDirectoryEntry.SchemaClassName != "Group")
continue;
string groupName = groupDirectoryEntry.Name;
Console.WriteLine("Checking: {0}", groupName);
if (IsUserMemberOfGroup(groupDirectoryEntry, String.Format("WinNT://{0}/{1}", domainName, userAccountName)))
{
groups.Add(groupName);
}
}
return groups;
}
private static bool IsUserMemberOfGroup(DirectoryEntry group, string userPath)
{
return (bool)group.Invoke(
"IsMember",
new object[] { userPath }
);
}
The call is something like this:
GetUserLocalGroups("samaccountname", "computerName.yourdomain", "yourdomain");