I have a requirement to get the current logged in user's group in SharePoint Online. The current logged in user is in an Active Directory Group residing in a SharePoint Group. When I am using the Rest API to query the group it does not return the group where user is added via AD group. Is there a way to get the logged in user's group for this scenario?
1 Answer
You can achieve this using SPFx + PnP JS + Microsoft Graph API.
High-level steps are as below:
- It is assumed that you already have a SPFx solution. Install PNP JS and
- Microsoft Graph API libraries using command:
npm install @pnp/sp @pnp/graph @microsoft/microsoft-graph-client --save
Make sure your app registration in Azure AD has the necessary permissions to read group membership. You might needGroup.Read.All
andUser.Read.All
permissions. - React JS component to implement this functionality:
import * as React from 'react';
import { sp } from '@pnp/sp/presets/all';
import { graph } from '@pnp/graph';
import { MSGraphClient } from '@microsoft/sp-http';
class UserGroups extends React.Component {
constructor(props) {
super(props);
this.state = {
spGroups: [],
userAdGroups: {},
};
}
componentDidMount() {
this.getUserSharePointGroups();
}
getUserSharePointGroups = async () => {
try {
const currentUser = await sp.web.currentUser.get();
const spGroups = await sp.web.siteGroups();
const userSpGroups = [];
const userAdGroups = {};
for (const group of spGroups) {
const groupUsers = await sp.web.siteGroups.getById(group.Id).users();
const isMember = groupUsers.some(user => user.Email === currentUser.Email);
if (isMember) {
userSpGroups.push(group);
// Fetch AD groups for each user in the SharePoint group
for (const user of groupUsers) {
const adGroups = await this.getUserAdGroups(user.Email);
userAdGroups[user.Email] = adGroups;
}
}
}
this.setState({ spGroups: userSpGroups, userAdGroups });
} catch (error) {
console.error("Error fetching user groups:", error);
}
};
getUserAdGroups = async (email) => {
try {
const client = await this.props.context.msGraphClientFactory.getClient();
const adGroups = await client.api(`/users/${email}/memberOf`).get();
return adGroups.value.filter(group => group['@odata.type'] === '#microsoft.graph.group').map(group => group.displayName);
} catch (error) {
console.error("Error fetching AD groups:", error);
return [];
}
};
render() {
return (
<div>
<h1>User SharePoint and AD Groups</h1>
{this.state.spGroups.map(group => (
<div key={group.Id}>
<h2>{group.Title}</h2>
<ul>
{this.state.userAdGroups[group.Email]?.map((adGroup, index) => (
<li key={index}>{adGroup}</li>
))}
</ul>
</div>
))}
</div>
);
}
}
export default UserGroups;