Checking if a SharePoint user exist in an AD Group

Common requirement is from SharePoint either within your custom webpart or control you’d want to implement some custom functionality to check if the current logged in user is a member of a specific AD group.

The following helper method should help out:

public static bool IsCurrentUserMemberOfGroup(string groupName)
{
var returnValue = false;
var userLogin = SPContext.Current.Web.CurrentUser.LoginName;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
var principalContext = new PrincipalContext(ContextType.Domain);
var userPrincipal = UserPrincipal.FindByIdentity(principalContext, System.DirectoryServices.AccountManagement.IdentityType.SamAccountName, userLogin);
var group = GroupPrincipal.FindByIdentity(principalContext, groupName);
returnValue = group.Members.Any(x => x.SamAccountName == userPrincipal.SamAccountName);
//returnValue = userPrincipal.IsMemberOf(group);
});
return returnValue;
}