Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
8.3k views
in SharePoint Online by 6 6 8
In SharePoint modern page, I am trying to create SPFX web part to show and hide content per the current user group who belong to? so I am asking Is it possible to check if the current user is amember in a specific group in SPFX web part or script editor web part?

1 Answer

1 like 0 dislike
by 90 163 334
selected by
 
Best answer

You have two options to check if the current user is a member of a specific group in SharePoint SPFX as the following:

  1. Using REST API
  2. Using Microsoft Graph

1) Check if current user is a member of group using REST API in SharePoint

To get the list of groups in which a user is a member, you can use this endpoint _api/Web/CurrentUser/Groups

function checkMemberGroups() {
    var absoluteUri = _spPageContextInfo.webAbsoluteUrl;
    var UserInGroup = false;
    var UserGroup = "Enter your group name that you would like to check"
    $.ajax({
            async: false,
            headers: {
                "accept": "application/json; odata=verbose"
            },
            method: "GET",
            url: absoluteUri + "_api/Web/CurrentUser/Groups",
            success: function(data) {

                success: function(data) {
                    for (var i = 0; i < data.d.Groups.results.length; i++) {

                        if (data.d.Groups.results[i].Title == UserGroup) {
                            UserInGroup = true;
                        }
                    }

                },
                error: function(response) {
                    console.log(response.status);
                },
            });
        return UserInGroup;
    }

You can use the above function in a Script editor. also, don't forget to provide your group name.

Besides, the above code, you can use the same endpoint _api/Web/CurrentUser/Groups in your SPFX web part by using import { SPHttpClient } from '@microsoft/sp-http';

this.context.spHttpClient.get(this.context.pageContext.site.absoluteUrl + "_api/Web/CurrentUser/Groups",
        SPHttpClient.configurations.v1)
    .then((groupResponse: SPHttpClientResponse) => {
        groupResponse.json().then((groupsData: any) => {
            var groups = groupsData.value;

            groups.forEach(group => {
                if (group.Title == "**your group name**") {
                    // your code
                }
            });
        });
    });

2) Check if the current user is a member of a group using Microsoft Graph in SharePoint

You can use checkMemberGroups and user: getMemberGroups to return all the groups that the user is a member of.

If you don’t ask, the answer is always NO!
...