Dipende su cosa intendi se un utente si trova in un gruppo di annunci. In AD, i gruppi possono essere un gruppo di sicurezza o un gruppo di distribuzione. Anche per i gruppi di sicurezza, dipende dal fatto che gruppi come "Domain Users" o "Users" devono essere inclusi nel controllo di appartenenza.
IsUserInSecurityGroup controllerà solo i gruppi di sicurezza e funzionerà per gruppi di gruppi principali come "Utenti dominio" e "Utenti" e non gruppi di distribuzione. Risolverà anche il problema con i gruppi nidificati. IsUserInAllGroup controlla anche i gruppi di distribuzione, ma non sono sicuro che si verifichino problemi di autorizzazione. In tal caso, utilizzare un account di servizio in WAAG (See MSDN)
La ragione per cui non sto utilizzando UserPrincipal.GetAuthorizedGroups() è perché ha un sacco di problemi, come richiedere l'account di chiamata per essere in WAAG e che richiede non v'è una voce nel SidHistory (See David Thomas' comment)
public bool IsUserInSecurityGroup(string user, string group)
{
return IsUserInGroup(user, group, "tokenGroups");
}
public bool IsUserInAllGroup(string user, string group)
{
return IsUserInGroup(user, group, "tokenGroupsGlobalAndUniversal");
}
private bool IsUserInGroup(string user, string group, string groupType)
{
var userGroups = GetUserGroupIds(user, groupType);
var groupTokens = ParseDomainQualifiedName(group, "group");
using (var groupContext = new PrincipalContext(ContextType.Domain, groupTokens[0]))
{
using (var identity = GroupPrincipal.FindByIdentity(groupContext, IdentityType.SamAccountName, groupTokens[1]))
{
if (identity == null)
return false;
return userGroups.Contains(identity.Sid);
}
}
}
private List<SecurityIdentifier> GetUserGroupIds(string user, string groupType)
{
var userTokens = ParseDomainQualifiedName(user, "user");
using (var userContext = new PrincipalContext(ContextType.Domain, userTokens[0]))
{
using (var identity = UserPrincipal.FindByIdentity(userContext, IdentityType.SamAccountName, userTokens[1]))
{
if (identity == null)
return new List<SecurityIdentifier>();
var userEntry = identity.GetUnderlyingObject() as DirectoryEntry;
userEntry.RefreshCache(new[] { groupType });
return (from byte[] sid in userEntry.Properties[groupType]
select new SecurityIdentifier(sid, 0)).ToList();
}
}
}
private static string[] ParseDomainQualifiedName(string name, string parameterName)
{
var groupTokens = name.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries);
if (groupTokens.Length < 2)
throw new ArgumentException(Resources.Exception_NameNotDomainQualified + name, parameterName);
return groupTokens;
}
fonte
2013-01-30 21:07:55
Come per la risposta di BC, il codice precedente non testerà l'appartenenza nidificata –
Questo codice non è nemmeno compilato in 3.5 C#, qual è l'accordo? – Justin