2

我正在创建一个PrincipalContext对象,用于从AD数据库中检索用户的组(我们使用这些身份验证来验证网站的各个部分)。使用Windows身份验证创建PrincipalContext

这习惯使用窗体身份验证来完成,所以代码看起来是这样的

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

UserPrincipal usp = 
    UserPrincipal.FindByIdentity(pc, IdentityType.Guid, user.Guid.ToString()); 

foreach (var group in usp.GetGroups()) 
{ 
    // Add group to collection 
} 

然而,我们最近切换到Windows身份验证,我不再能够访问用户的密码。

如何使用当前用户的凭据搜索AD数据库?我试过使用模拟,但它在FindByIdentity行上抛出An operations error occurred错误。如果我忘记了所有身份验证,我只限于返回的组数。

+0

当你说现在的用户,你的意思是用户运行该exe文件? – Botonomous

+0

@Anon对不起,我应该提到这是一个asp.net内联网站点。我的意思是用户浏览网页。 –

回答

6

这里是我使用的方法,你可以改变它返回一个集合:

public static List<string> getGrps(string userName)   
{   
    List<string> grps = new List<string>();   

    try   
    { 
     var currentUser = UserPrincipal.Current; 
     RevertToSelf();    
     PrincipalSearchResult<Principal> groups = currentUser.GetGroups();   
     IEnumerable<string> groupNames = groups.Select(x => x.SamAccountName);   
     foreach (var name in groupNames)   
     {   
      grps.Add(name.ToString());   
     }   
     return grps;   
    }   
    catch (Exception ex)   
    {   
     // Logging   
    }   
} 

我假设你想要的结果IEnumerable的,这就是我在这里做。

+0

谢谢!这似乎对我有用,而且比我想要做的要容易得多。 –

+0

@Cavyn VonDeylen我很高兴为你工作! – Botonomous

0

Anon的答案适用于我所问的内容,但我也希望能够搜索其他用户的群组。我发现这样做的最好方法是在服务帐户下运行asp.net程序的应用程序池,然后使用我的原始代码。

要在IIS Manager 7.5中执行此操作,请转至应用程序池,右键单击您的应用程序正在运行的应用程序 - >高级设置,然后将标识从“ApplicationPoolIdentity”更改为自定义域帐户。