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
To use it in the solution let us add the reference in the webpart file.
- import * as msal from "@azure/msal-browser";
Add the below constant variables , replace <clientid> with the client id generated above after registering Azure AD application and replace <redirecturi> with the redirect Uri where we want to use the solution (in the below code we have used the workbench).
- 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