Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# N用户标识,然后启用模拟。可以通过IIS或通过在web.config中添加以下元素来启用模拟 <system.web> <identity impersonate="true"/>_C#_Asp.net_Active Directory - Fatal编程技术网

C# N用户标识,然后启用模拟。可以通过IIS或通过在web.config中添加以下元素来启用模拟 <system.web> <identity impersonate="true"/>

C# N用户标识,然后启用模拟。可以通过IIS或通过在web.config中添加以下元素来启用模拟 <system.web> <identity impersonate="true"/>,c#,asp.net,active-directory,C#,Asp.net,Active Directory,注意:组必须用反斜杠书写,即“TheDomain\TheGroup”这对我很有用 public string[] GetGroupNames(string domainName, string userName) { List<string> result = new List<string>(); using (PrincipalContext principalContext = new PrincipalContext(Co

注意:组必须用反斜杠书写,即“TheDomain\TheGroup”

这对我很有用

public string[] GetGroupNames(string domainName, string userName)
    {
        List<string> result = new List<string>();

        using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName))
        {
            using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(principalContext, userName).GetGroups())
            {
                src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
            }
        }

        return result.ToArray();
    }
public string[]getGroupName(字符串域名,字符串用户名)
{
列表结果=新列表();
使用(PrincipalContext PrincipalContext=new PrincipalContext(ContextType.Domain,domainName))
{
使用(PrincipalSearchResult src=UserPrincipal.FindByIdentity(principalContext,userName.GetGroups())
{
src.ToList().ForEach(sr=>result.Add(sr.SamAccountName));
}
}
返回result.ToArray();
}

答案取决于要检索的组类型。
System.DirectoryServices.AccountManagement
命名空间提供了两种组检索方法:

-返回组对象的集合,这些对象指定当前主体是其成员的组

这个重载方法只返回主体是其直接成员的组;不执行递归搜索

-返回主体对象的集合,其中包含此用户所属的所有授权组。此函数仅返回属于安全组的组;不返回通讯组

此方法递归搜索所有组,并返回用户所属的组。返回的集合还可以包括系统将考虑用户作为授权目的的成员的附加组。

因此,
GetGroups
获取用户是其直接成员的所有组,而
GetAuthorizationGroups
获取用户是其直接或间接成员的所有组

尽管它们的命名方式不同,但其中一个并不是另一个的子集。可能存在由
GetGroups
返回的组,而不是由
GetAuthorizationGroups
返回的组,反之亦然

下面是一个用法示例:

// (replace "part_of_user_name" with some partial user name existing in your AD)
var userNameContains = "part_of_user_name";

var identity = WindowsIdentity.GetCurrent().User;
var allDomains = Forest.GetCurrentForest().Domains.Cast<Domain>();

var allSearcher = allDomains.Select(domain =>
{
    var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://" + domain.Name));

    // Apply some filter to focus on only some specfic objects
    searcher.Filter = String.Format("(&(&(objectCategory=person)(objectClass=user)(name=*{0}*)))", userNameContains);
    return searcher;
});

var directoryEntriesFound = allSearcher
    .SelectMany(searcher => searcher.FindAll()
        .Cast<SearchResult>()
        .Select(result => result.GetDirectoryEntry()));

var memberOf = directoryEntriesFound.Select(entry =>
{
    using (entry)
    {
        return new
        {
            Name = entry.Name,
            GroupName = ((object[])entry.Properties["MemberOf"].Value).Select(obj => obj.ToString())
        };
    }
});

foreach (var item in memberOf)
{
    Debug.Print("Name = " + item.Name);
    Debug.Print("Member of:");

    foreach (var groupName in item.GroupName)
    {
        Debug.Print("   " + groupName);
    }

    Debug.Print(String.Empty);
}
}
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "MyDomain", "OU=AllUsers,DC=MyDomain,DC=Local");
UserPrincipal inputUser = new UserPrincipal(domainContext);
inputUser.SamAccountName = "bsmith";
PrincipalSearcher adSearcher = new PrincipalSearcher(inputUser);
inputUser = (UserPrincipal)adSearcher.FindAll().ElementAt(0);
var userGroups = inputUser.GetGroups();
我的解决方案:

UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, myDomain), IdentityType.SamAccountName, myUser);
List<string> UserADGroups = new List<string>();            
foreach (GroupPrincipal group in user.GetGroups())
{
    UserADGroups.Add(group.ToString());
}
UserPrincipal user=UserPrincipal.FindByIdentity(新PrincipalContext(ContextType.Domain,myDomain),IdentityType.SamAccountName,myUser);
List UserADGroups=新列表();
foreach(user.GetGroups()中的GroupPrincipal组)
{
添加(group.ToString());
}

@Tassisto:是的,他理解你。上面的代码片段将完全按照您的喜好执行。只需将最终的foreach循环替换为生成组名列表的循环,而不是调试打印。它将无法列出用户的主要组(通常是域用户)。您必须返回并单独查询该信息。GetAuthorizationGroups没有此问题。@Tassisto:不幸的是,该属性不能直接在
UserPrincipal
上使用-请参阅我的更新答案以了解如何使用它。我需要提供用户名以获取其部门的值-field@Tassito:那么1)创建域上下文,2)按用户名查找该用户,3)使用我的代码片段获取其部门GetGroups方法对我不起作用,我更改了新的主体上下文以使用另一个重载构造函数,如下所示:PrincipalContext yourDomain=new PrincipalContext(ContextType.Domain,“192.168.2.23”,“Domain\user”,“password”);这是完全合乎逻辑的,因为您并不总是通过active directory身份验证登录。希望能有所帮助。这个答案很好。还可以将组迭代简化为:result.AddRange(user.GetAuthorizationGroups().OfType())如果您在web应用程序中为服务/应用程序池帐户使用内置帐户,则可能会出现这种情况。如果您将域帐户用作服务/应用程序池帐户,或在代码中模拟域帐户,则默认情况下它应该具有读取权限,而不是此问题。使用此技术而不是r可以提高性能正在浏览广告。谢谢!GetAuthorizationGroups()对我来说是非常慢的,例如26和所有其他代码,我发现到目前为止,没有包括众所周知的标识符,如每个人,域用户等。你提供的代码是即时的,包括所有的SID,是的,只有SID,但这是我需要的,包括众所周知的和自定义的!太棒了!Thanx。我开始编写一些代码,是我们正在初始化GetAuthorizationGroups,并对需要300ms-2.5s才能获取所有组感到震惊。您的方法在20-30ms内完成。这似乎很有希望,但它无法解析嵌套组,例如,用户是组a的成员,而组a本身就是组x的成员。上面的代码只显示组a,而不是组x。我通过tokenGroups:t使用此方法看一看Robert Muehsig的评论——这不支持嵌套组,而且速度更快。唯一的缺点是它只返回安全组,而不返回分发组Groups@bigjim无法使用GetAuthorizationGroups,因为返回其数据需要将近6秒的时间,但您提供的代码不会返回众所周知的组,如Everyone、Domain Users等…以及所有东西似乎只返回“自定义组”,而不是用户所属的所有组。
using System.Security.Principal

private List<string> GetGroups(string userName)
{
    List<string> result = new List<string>();
    WindowsIdentity wi = new WindowsIdentity(userName);

    foreach (IdentityReference group in wi.Groups)
    {
        try
        {
            result.Add(group.Translate(typeof(NTAccount)).ToString());
        }
        catch (Exception ex) { }
    }
    result.Sort();
    return result;
}
var pc = new PrincipalContext(ContextType.Domain, domain, "USER_WITH_PERMISSION", "PASS");
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
var groups = user.GetGroups();
// Usage: GetAdGroupsForUser2("domain\user") or GetAdGroupsForUser2("user","domain")
public static List<string> GetAdGroupsForUser2(string userName, string domainName = null)
{
    var result = new List<string>();

    if (userName.Contains('\\') || userName.Contains('/'))
    {
        domainName = userName.Split(new char[] { '\\', '/' })[0];
        userName = userName.Split(new char[] { '\\', '/' })[1];
    }

    using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domainName))
        using (UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, userName))
            using (var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://" + domainContext.Name)))
            {
                searcher.Filter = String.Format("(&(objectCategory=group)(member={0}))", user.DistinguishedName);
                searcher.SearchScope = SearchScope.Subtree;
                searcher.PropertiesToLoad.Add("cn");

                foreach (SearchResult entry in searcher.FindAll())
                    if (entry.Properties.Contains("cn"))
                        result.Add(entry.Properties["cn"][0].ToString());
            }

    return result;
}
<system.web>
<identity impersonate="true"/>
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
If HttpContext.Current.User.IsInRole("TheDomain\TheGroup") Then
//code to do when user is in group
End If
public string[] GetGroupNames(string domainName, string userName)
    {
        List<string> result = new List<string>();

        using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName))
        {
            using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(principalContext, userName).GetGroups())
            {
                src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
            }
        }

        return result.ToArray();
    }
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "MyDomain", "OU=AllUsers,DC=MyDomain,DC=Local");
UserPrincipal inputUser = new UserPrincipal(domainContext);
inputUser.SamAccountName = "bsmith";
PrincipalSearcher adSearcher = new PrincipalSearcher(inputUser);
inputUser = (UserPrincipal)adSearcher.FindAll().ElementAt(0);
var userGroups = inputUser.GetGroups();
UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, myDomain), IdentityType.SamAccountName, myUser);
List<string> UserADGroups = new List<string>();            
foreach (GroupPrincipal group in user.GetGroups())
{
    UserADGroups.Add(group.ToString());
}