Saturday, 27 August 2011

Check if current sharepoint user is a member of an AD group


The Below method will check if the current user is a part of an AD group.

bool memberInGroup = false;
SPUser currentUser = SPContext.Current.Web.CurrentUser;
String username = currentUser.LoginName;

//Check if user is a part of one of the AD groups
if (IsUserInADGroup("AdGroupName", username))
{
memberInGroup = true;
}

protected bool IsUserInADGroup(string groupName, string username)
{
bool reachedMax;

SPPrincipalInfo[] groupUsers =
SPUtility.GetPrincipalsInGroup(SPContext.Current.Web, groupName, 100, out reachedMax);

// No Users in the Group was found
if (groupUsers == null || groupUsers.Length == 0)
{
return false;
}
else
{
// Loop through users in the AD Group
foreach (SPPrincipalInfo _user in groupUsers)
{
if (!_user.IsSharePointGroup && _user.PrincipalType != SPPrincipalType.SecurityGroup)
{
//Check for Our User
if (_user.LoginName.Trim() == username.Trim())
{
return true;
}
}
}
return false;
}
}

Ads by Google

No comments:

Post a Comment