Check SharePoint Current loggedin user in Active directory

The code snippet ( in Method 1) below Looks up the Current Logged in user into the Active Directory group. If you simply want to check if the user exist in one of the Ad groups which is added inside your sharepoint group, you can use Method 2 specified below.

Method 1 -

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;
}
}

Method 2 -
If you want to check that a user is a part of one of your AD groups which is added into your SharePoint group, you can try using the following

bool memberInGroup = false;
SPGroup group = null;

group = SPContext.Current.Web.Groups["SharePointGroupName"];

if (group != null)
{
if(group.ContainsCurrentUser)
memberInGroup = true;
}

0 comments:

Post a Comment

Disclaimer

This is a personal weblog. The opinions expressed here represent my own and not those of my employer or anyone else. Should you have any questions or concerns please e-mail me at sharepointprogrammingblogger@gmail.com .

Copyright (c) 2010 @ myshaepointwork.blogspot.com. All rights are reserved.Do Not Copy.

@ Learning SharePoint.com