我有一个应用程序需要绑定到远程客户的 Active Directory 以执行身份验证任务。
using (var ctx = new PrincipalContext(ContextType.Domain, "customer.org", "ou=people,dc=customer,dc=org", ContextOptions.SecureSocketLayer | ContextOptions.SimpleBind, "bindaccount@customer.org", "password"))
{
var user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username); // after several seconds, throws PrincipalServerDownException
if (user == null) return null; // user doesn't exist
// check if the account is locked out, etc. (omitted)
// quickly validate credentials
if (!ctx.ValidateCredentials(username, password, ContextOptions.SecureSocketLayer | ContextOptions.SimpleBind)) return null; // bad credentials
return user;
}
例外是:
PrincipalServerDownException:服务器无法运行。
at System.DirectoryServices.AccountManagement.ADStoreCtx.GetAsPrincipal(Object storeObject, Object discriminant)
at System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRefHelper(Type principalType, String urnScheme, String urnValue, DateTime referenceDate, Boolean useSidHistory)
at System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRef(Type principalType, String urnScheme, String urnValue, DateTime referenceDate)
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate)
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, IdentityType identityType, String identityValue)
at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue)
直到今天,一切都很好。一个变化是运行此代码的应用程序从 4 升级到 4.5。我不能确定问题是在升级后立即发生的,还是只是巧合。
我一直在使用 AdFind 来测试与客户 AD 的绑定,它似乎工作正常。
另一个有趣的事情是PrincipalContext
初始化很好(从而验证了它与远程存储的连接),如果我注释掉FindByIdentity
调用ctx.ValidateCredentials
,那么它也可以正常工作。