Is the logged in user a member of a given AD group
Code:
/// <summary>
/// Returns true if the current logged on user is a member
/// of the given active directory group
/// </summary>
/// <param name="groupname">
/// The name of the active directory group to check
/// </param>
/// <remarks>
/// If we pass a group name with no root (e.g. no EMEA APAC etc) then
/// the users own root needs to be used,
/// </remarks>
/// <returns></returns>
public static bool IsUserInGroup(string groupname)
{
if (string.IsNullOrEmpty(groupname))
{
return true;
}
else
{
bool _return = false;
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal _user = (WindowsPrincipal)System.Threading.Thread.CurrentPrincipal;
WindowsIdentity _ident = (WindowsIdentity)_user.Identity;
string _domainName = @"";
string _groupname = @"";
if (groupname.Contains(@"\"))
{
// use the domain specified
_domainName = groupname.Substring(0, groupname.IndexOf(@"\") );
_groupname = groupname.Substring(groupname.IndexOf(@"\") + 1);
}
else
{
// use the current user domain
string _username = _ident.Name;
if (_username.Contains(@"\"))
{
_domainName = _username.Substring(0, _username.IndexOf(@"\") );
}
_groupname = groupname;
}
foreach (IdentityReference group in _ident.Groups )
{
NTAccount account = null;
try
{
account = (NTAccount)group.Translate( typeof( NTAccount ) );
}
catch ( IdentityNotMappedException )
{ }
catch ( UnauthorizedAccessException )
{ }
catch ( SystemException )
{ }
if ( account != null )
{
if (account.Value.Equals(_domainName + @"\" + _groupname, StringComparison.OrdinalIgnoreCase))
{
_return = true;
break;
}
}
}
return _return;
}
}
Re: Is the logged in user a member of a given AD group
Thank you so much. Works like a champ.