Overview
In this blog we will use REST API V2 in SharePoint Framework SPFx to fetch data. We will not use isolated webparts in SPFx but will use MSAL.js 2.0
For more detail on MSAL.js 2.0 please follow the link below
https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-browser
Step 1 - Create an Azure AD Application
To provide access and to fetch the bearer token we need to create an Azure AD Application with required API permission. To create Azure AD application use the below steps,
- Navigate to https://portal.azure.com
- Select Azure Active Directory
- Navigate to App registration
- Click on New registration

- Enter the appropriate application name
- Add the redirection URL and in the dropdown; instead of web select Single-page-application (SPA)

- Add API Permission for SharePoint API V2 and Grant Admin Consent
- Copy the client Id which got created which will be used.

Step 2
Create an SPFx Solution
Step 3 - Add MSAL.js 2.0 to Solution
To add reference to the solution use the below command which is available from npm
- npm i @azure/msal-browser
- import * as msal from "@azure/msal-browser";
- const msalConfig = {
- auth: {
- clientId: '<clientId>',
- redirectUri: 'https://testinglala.sharepoint.com/_layouts/15/workbench.aspx'
- }
- };
- const msalInstance = new msal.PublicClientApplication(msalConfig);
Now let us use different scopes which we want to get the current user to login.
For the complete code follow this link
- let silentRequest = {
- scopes: ["https://testinglala.sharepoint.com/TermStore.Read.All", "https://testinglala.sharepoint.com/TermStore.ReadWrite.All"],
- loginHint: this.props.webpartContext.pageContext.user.email
- };
- msalInstance.ssoSilent(this.silentRequest).then((response) => {
- msalInstance.acquireTokenSilent(silentRequest).then((val) => {
- let headers = new Headers();
- let bearer = "Bearer " + val.accessToken;
- headers.append("Authorization", bearer);
- let options = {
- method: "GET",
- headers: headers
- };
- fetch("https://testinglala.sharepoint.com/_api/v2.1/termStore/groups", options)
- .then(resp => {
- resp.json().then((groups) => {
- console.log(groups);
- }).catch((errorint) => {
- console.log(errorint);
- });
- });
- }).catch((errorinternal) => {
- console.log(errorinternal);
- });
- }).catch((error) => {
- console.log(error);
- });
Outcome


amirPosted Nov 11, 2022, 5:20 PM
Hi, its not working with teams desktop.Any Idea ??
Richard GiganPosted Nov 3, 2021, 7:46 AM
Hi, i tried your good exemple, but, why not use AadHttpClient instead of MSAL? (I didn't manage to do it, maybe that's why you don't)