使用`new PrincipalContext(ContextType.Domain,“domain.name.com”)`而不必提供用户名和密码

时间:2015-02-11 22:27:22

标签: c# active-directory ldap

我已经构建了一个将与ClickOnce一起部署的应用程序,该应用程序在启动时需要检查当前登录用户的身份/名称,并将其与我们域中的Active Directory组进行比较为了在应用程序中设置适当的权限。

我可以通过"硬编码"应用程序中的用户名和密码,并将这些凭据传递给PrincipalContext构造函数,即

var pc = new PrincipalContext(ContextType.Domain, "domain.name.com", username, password);

问题在于我不想将用户名和密码存储在应用程序中(我也不想提示用户输入用户名和密码)。< / p>

我在网上看过很多使用构造函数而不指定凭据的示例,但这对我们的域名不起作用。

域名中是否有设置/权限或域名用户&#34;我可以配置哪些组属性来实现此功能?

我目前的代码如下(注意:

/// <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;
}

我基本上打电话是这样的:

var userGroups = GetUserGroups(WindowsIdentity.GetCurrent.Name, "server.domain.com");

2 个答案:

答案 0 :(得分:2)

&#34;您已经在线使用构造函数看到很多示例而未指定凭据&#34; 只要您的计算机属于域和用户,这应该适用于您的计算机已登录。

对我来说,错误可能来自于您使用时的事实:

var pc = new PrincipalContext(ContextType.Domain, domain);

domain应该是域名,如果用户登录到域,则由环境变量USERDNSDOMAIN给出,而不是&#34;域服务器的名称,例如,当你写入评论时,服务器.domain.com&#34;

答案 1 :(得分:0)

与以下行为类似:

PrincipalContext ctx;

if(this.UserEntityContext.IsLocalLogin == true)
{
    ctx = new PrincipalContext(ContextType.Machine);
}
else
{
    ctx = new PrincipalContext(ContextType.Domain);
}
UserPrincipal currentUser = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, _userInfo.UserID);

PrincipalSearchResult<Principal> groups = currentUser.GetAuthorizationGroups();

工作正常,但不适用于Citrix服务器场。发生(致命)错误,表示... ldap属性oder值不存在... 但不要说什么:-/

正在研究...