Search code examples
reactjsazure-ad-msalreact-aad-msal

Finding Azure/AD groups with React-AAD-MSAL


I have integrated basic authentication with the React-Aad-MSAL client into a my react-app which allows me to get things like the users name and email successfully. Here in a component I wanted to check the users groups before displaying some data.

import React, { useContext } from 'react'
import { observer } from 'mobx-react-lite'
import { Container, Header } from 'semantic-ui-react';
import {
    AzureAD,
    AuthenticationState,
    IAzureADFunctionProps
  } from "react-aad-msal";
import { authProvider } from '../../../app/auth/authProvider';
import { RootStoreContext } from '../../../app/stores/rootStore';

const PurchasePipelineDashboard: React.FC = () => {
    const rootStore = useContext(RootStoreContext)
    const {
        idTokenClaimsAction } = rootStore.serverCatalogStore;

    return (
        // <Container style={{marginTop:'7em'}}>
        //     <Header content="Purchase Pipeline" />
        // </Container>
        <AzureAD provider={authProvider} >
        {({
          accountInfo,
          authenticationState,
          error
        }: IAzureADFunctionProps) => {
          return (
            <React.Fragment>
              {authenticationState === AuthenticationState.Unauthenticated && (
                  <h1>Oooo weee!</h1>
              )}
            </React.Fragment>
          );

        }}
      </AzureAD>
    )   
}

export default observer(PurchasePipelineDashboard);

My question is; how would I go about gathering what groups the user is in? I have checked the accountInfo.account.idTokenClaims, but none of those return tokens. I see other tutorials using Graph, but do I actually need both libraries? Any help would be greatly appreciated!


Solution

  • You have two options here, you can either add them to the claims in the token as per here: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-optional-claims#configuring-groups-optional-claims but there are limitations, such as it will only return something like 150-200 groups max.

    or you can make a separate graph api call to get users groups. Here's an example of how to call graph with react https://github.com/microsoftgraph/msgraph-training-reactspa

    You would be looking at the getmembergroups endpoint of graph for this: https://learn.microsoft.com/en-us/graph/api/user-getmembergroups?view=graph-rest-1.0&tabs=http