LdapAuthentication を使用してユーザーを Active Directory にログインさせています。ユーザーが属するすべてのグループを検索したい。次のコードを使用しています。
string adPath = "LDAP://OU=HR Controlled Users,OU=All Users,DC=myDomain,DC=local";
LdapAuthentication adAuth = new LdapAuthentication(adPath);
try
{
if (true == adAuth.IsAuthenticated("myDomain", txtLoginEmail.Text, txtLoginPassword.Text))
{
string email = txtLoginEmail.Text;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.Name, email);
foreach (var group in user.GetGroups())
{
Console.WriteLine(group.Name);
}
}
}
}
catch(Exception e) { /* Handle Error */ }
私の問題は、 UserPrincipal.FindByIdentity() を呼び出すと、ユーザー認証が意図したとおりに機能しているにもかかわらず、常に null 値を取得することです。
なぜこうなった?コードまたは私のアプローチに問題はありますか? これは、ASP.NET 4.0 WebForms アプリケーション内で実行されています。
アップデート:
どうやら間違った IdentityType (cn) を使用していたようです。デバッグでチェックインしたところ、アカウントの名前は「UserA」です。
そこで、次のコードを手動で使用してみました。
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.Name, "UserA");
しかし、それでも私はnullになります。
更新 2 (解決済み):
問題は 2 つありました。を宣言するときに、ドメイン コントローラーの名前を指定する必要がありましたPrincipalContext
。
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "myDomain"))
{
// code here...
}
次に、を検索するときにUserPrincipal
、間違ったIdentityType
;を使用していました。ユーザー名であるIdentityType.Name
- ではなく、アカウントの名前である - で検索していました。IdentityType.SamAccountName
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, email);
問題が解決しました。