To check if a user is in a SharePoint Group (which also checks if the user is in an AD Group within that SharePoint group), use the following code:
using System.DirectoryServices.AccountManagement;
public bool IsUserInSharePointGroup(string webUrl, string groupName, string username)
{
bool userIsInGroup = false;
SPSecurity.RunWithElevatedPrivileges(delegate
{
try
{
SPWeb web = SPContext.Current.Web;
// Find the group
SPGroup group = web.SiteGroups[groupName];
string upperCaseUserName = username.ToUpper();
foreach (SPUser user in group.Users)
{
// Check if this is an AD Group
if (!user.IsDomainGroup)
{
// Verify if the user name matches the user name in group
if (user.LoginName.ToUpper().Equals(upperCaseUserName))
{
userIsInGroup = true;
return;
}
}
else
{
// this is an AD group
var pc = new PrincipalContext(ContextType.Domain);
var myuser = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, username);
var mygroup = GroupPrincipal.FindByIdentity(pc, user.LoginName);
if (myuser.IsMemberOf(mygroup))
{
userIsInGroup = true;
return;
}
}
}
}
catch (Exception ex)
{
//Trace error
}
});
return userIsInGroup;
}