I've built an application that will be deployed with ClickOnce that, upon startup, will need to check the currently logged in user's Identity/Name, and compare it to the Active Directory Groups on our domain in order to set up appropriate permissions in the application.
I can do this by "hard coding" a username and password into the application, and passing these credentials into the PrincipalContext
constructor, i.e.,
var pc = new PrincipalContext(ContextType.Domain, "domain.name.com", username, password);
The problem is that I don't want to have to store the username and password in the application (and I don't want to have to prompt the user for their username and password, either).
I've seen many examples online using the constructor without specifying credentials, but this doesn't work on our domain.
Is there a setting/permission in the Domain or "Domain Users" Group properties that I can configure to get this to work?
My current code is as follows (note that :
/// <summary>
/// Gets a list of all Active Directory Groups the specified username is a member of.
/// </summary>
/// <param name="userName">The username of the user in DOMAIN\Username format</param>
/// <param name="domain">The name of the domain server, e.g., server.domain.com (not DOMAIN or DOMAIN.COM or SERVER)</param>
/// <returns></returns>
public static List<string> GetUserGroups(string userName, string domain)
{
if (userName.IsNullOrWhiteSpace()) return null;
var pc = new PrincipalContext(ContextType.Domain, domain);
var userPc = UserPrincipal.FindByIdentity(pc, userName);
if (userPc == null) return null;
var src = userPc.GetGroups(pc);
var result = new List<string>();
src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
return result;
}
And I'm essentially calling is like this:
var userGroups = GetUserGroups(WindowsIdentity.GetCurrent.Name, "server.domain.com");
"You've seen many examples online using the constructor without specifying credentials" This should work on your machine as far as your computer belongs to the domain and the user is logged in.
For me the error can come from the fact that when you use :
var pc = new PrincipalContext(ContextType.Domain, domain);
domain
is supposed to be the domain name, given by the environnement variable USERDNSDOMAIN
if the user is logged into the domain, and not "The name of the domain server, e.g., server.domain.com" as you write into the comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With