Wednesday, November 19, 2008

Checking if logged in user is member of Sharepoint Site

To check if current logged in user is member of current site. We could loop through groups available for the current site and check if user is member of the group.

SPWeb object defines a method SPWeb.IsCurrentUserMemberOfGroup(int groupid). This method takes the credentials of logged in user and Group ID as parameter.
Group id can be obtained from SPGroup object. SPWeb object also has one property SPWeb.Groups. Simply loop through this collection and check if logged in user is member of this group.

Following code snippet checks if user is member of group (except visitor group).

SPWeb web = SPContext.Current.Web;
bool isMember = false;
foreach (SPGroup group in web.Groups)
//If it is visitors group, do not check user membership
if(group != web.AssociatedVisitorGroup)
isMember = web.IsCurrentUserMemberOfGroup(group.ID);
//Check if user is member of this site.
if (isMember==true)
if (isMember)
// other task to do if user is member

SPWeb class has properties that can be used to determine Visitors Groups/Members Groups and Groups associated with web site.

Gets a list of the groups that are associated with the Web site.
Gets the users who have been given contribute permissions to the Web site.
Gets or sets the associated owner groups of the Web site.
Gets or sets the associated visitor group of the Web site.

Sudhir Kesharwani


Anonymous said...

It is working with Windows Aauthentication, but whenever I try to run this with FBA authentacted site, it is giving error object reference not set...

Is it not work with FBA? I have used Sharepoint Group only.

Sudhir Kesharwani said...

I have not tried this with FBA. But as your rightly said,

most of the SharePoint stuff starts breaking when you use FBA :)