我正在努力解决一个简单的问题:我想使用用于登录计算机的用户名和密码从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");
这些同样不成功。
答案 0 :(得分:6)
本守则应该适合你肖恩 我目前正在研究AD for BOA并多次使用..
public bool UserExists(string username)
{
// create your domain context
PrincipalContext domain = new PrincipalContext(ContextType.Domain);
// find the user
UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);
return foundUser != null;
}
从MSDN 每个参数的内容见下面的列表 参数
context
Type: System.DirectoryServices.AccountManagement.PrincipalContext
The PrincipalContex that specifies the server or domain against which operations are performed.
identityType
Type: System.DirectoryServices.AccountManagement.IdentityType
A IdentityType enumeration value that specifies the format of the identityValue parameter.
identityValue
Type: System.String
The identity of the user principal. This parameter can be any format that is contained in the IdentityType enumeration.
Return Value
Type: System.DirectoryServices.AccountManagement.UserPrincipal
A UserPrincipal object that matches the specified identity value and type, or null if no matches are found.
答案 1 :(得分:6)
我相信不存在的对象是:
"OU=Users,DC=SLO1,DC=Foo,DC=Bar,DC=biz"
用户是容器,而不是OU。所以你需要正确:
"CN=Users,DC=SLO1,DC=Foo,DC=Bar,DC=biz"