【发布时间】:2013-01-04 17:43:10
【问题描述】:
我在一个简单的场景中苦苦挣扎:我想使用我用来登录我的计算机的用户名和密码从 Active Directory 中检索我的帐户。
我的第一个问题是我在尝试调用 UserPrincipal.FindByIdentity 时收到了来自服务器的推荐。我认为这有点奇怪,因为 PrincipalContext.ValidateCredentials 工作正常,但事实证明我的 DC 路径不正确。
我不确定如何正确制作我的 OU/DC 字符串。因此,我找到了this SO post 这有助于提供以下代码:
private static string GetDomainControllerString()
{
string pdc;
using (var context = new PrincipalContext(ContextType.Domain))
{
string server = context.ConnectedServer; // "pdc.examle.com"
string[] splitted = server.Split('.'); // { "pdc", "example", "com" }
IEnumerable<string> formatted = splitted.Select(s => String.Format("DC={0}", s));// { "DC=pdc", "DC=example", "DC=com" }
string joined = String.Join(",", formatted); // "DC=pdc,DC=example,DC=com"
// or just in one string
pdc = String.Join(",", context.ConnectedServer.Split('.').Select(s => String.Format("DC={0}", s)));
}
return pdc;
}
使用此代码正确生成我的 DC 字符串后,我的错误消息发生了变化。现在,我收到错误“服务器上没有这样的对象”。我怀疑问题出在我的 OU 或我如何调用 FindByIdentity。
这是我要检索的用户帐户的位置:
这是我尝试访问所述用户的方式:
private static void Main(string[] args)
{
const string Domain = "SLO1.Foo.Bar.biz";
const string DefaultOU = "OU=Users,DC=SLO1,DC=Foo,DC=Bar,DC=biz";
const string username = @"sanderso";
const string password = "**********";
var principalContext = new PrincipalContext(ContextType.Domain, Domain, DefaultOU, ContextOptions.Negotiate, username, password);
bool areCredentialsValid = principalContext.ValidateCredentials(username, password, ContextOptions.Negotiate);
if (areCredentialsValid)
{
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, username);
}
}
我也试过打电话:
UserPrincipal.FindByIdentity(principalContext, IdentityType.Name, "Sean Anderson");
UserPrincipal.FindByIdentity(principalContext, "Sean Anderson");
这些同样不成功。
【问题讨论】:
-
Sean 你的最后一个例子,你不必传入 Identity.Name,“Sean Anderson”尝试像这样删除 IdentityType.Name
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupSamAccountName);if(group != null) { / / 这为您提供了“SecurityIdentifier”类型的变量,用于 // 调用“IsInRole” .... SecurityIdentifier groupSid = group.Sid;字符串 groupSidSDDL = groupSid.Value; } -
任何关于它的最终源代码解决方案以验证凭据?
标签: c# active-directory directoryservices