0

I am trying to fetch data from a business Microsoft Sharepoint domain, in one of the locations it has a stored XLSX (excel) file that I need to analyze and upload to a database.

If I send a request via postman to the URL of the XLSX file I get a 403 forbidden (obviously I'm not authenticated)

So I'm trying to access an XLSX file stored on Microsoft Sharepoint and I need to authorize myself before I can access it with either react or nodejs.

Example URL: https://[ORGANIZATION_NAME].sharepoint.com/:x:/r/teams/[ORGANIZATION_TEAM_NAME]/_layouts/15/Doc.aspx?file=[FILENAME].xlsx

I am not sure where or how to authenticate myself with sharepoint to programmatically access that file. I searched and found many packages such as React-PNP, but I wasn't sure how to implement them to do what I wanted.

2 Answers2

1

According to my research and testing, you can use App-Only authentication to authenticate to SharePoint Online. In App-Only Authentication we need to create the "client-id" and "client secret". Please follow the steps in the following article to authenticate to SharePoint Online and grant access using SharePoint app-only: https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs

Also, if you want to fetching Data using React, you can refer to this document: SharePoint Framework - Fetching Data In React

Hope it can help you. Thanks for your understanding.

Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.

Zella_msft
  • 372
  • 2
  • 4
  • Thank you! I've yet to implement this fully, but this looks 100% like what I was looking. For any others who read this and are trying to use react or javascript, see the link below for help. https://github.com/s-KaiNet/node-sp-auth/wiki/SharePoint%20Online%20addin%20only%20authentication – Tobey Hainge Jan 24 '23 at 00:37
1

I ended up doing exactly what I wanted using React and NodeJS using the Microsoft Graph API. You can try example queries here https://developer.microsoft.com/en-us/graph/graph-explorer, some of which allow you to fetch and perform CRUD operations if needed or just simply fetch on a sharepoint excel file.

The only thing you need to use the queries directly in your React/NodeJS application is a token from a Microsoft authentication session. In order to use Microsoft's authentication session you will need to generate a private and public key in sharepoint.

Steps for registering your application and getting the key needed for client authentication...

  1. https://portal.azure.com/#home < azure active directory
  2. Add > App registration
  3. Accounts in any organizational directory (Any Azure AD directory - Multitenant)
  4. Single-page application: http://localhost:3000 http://localhost:3080
  5. Get application (client) ID
  6. Authentication > add a platform > Single page application
  7. redirect url: http://localhost:3000 && http://localhost:3080

Once this is done you are all set on sharepoint's end. All of this was just to get the client ID key for your app.

Now you will need to add this key to your react app. This can be done by going to your index.js and formatting it like so, to let the application recognize your app as a trusted authentication client.

You will need the npm packages "@microsoft/mgt-msal2-provider" & "@microsoft/mgt-element"

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Providers } from '@microsoft/mgt-element';
import { Msal2Provider } from '@microsoft/mgt-msal2-provider';

Providers.globalProvider = new Msal2Provider({
      clientId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
});

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <App />
);

Now your app is recognized as a trustworthy client and you can now test your authentication. Install the package "@microsoft/mgt-react" to access an easy authentication login component.

import { Login } from '@microsoft/mgt-react';

function App() {
    return (
        <Login />
    )
}

If everything was done correctly it should show a microsoft login component and you should be able to login to a microsoft account. This will give you a token which you can use to run Sharepoint queries using the microsoft graph api.

Example on how to get token

import { Providers } from "@microsoft/mgt";

function Test() {
const accessToken = await Providers.globalProvider.getAccessToken({ scopes: ['User.Read', 'Files.ReadWrite'] })
console.log(accessToken) // Returns token!
}

With your token you can now run queries to your sharepoint excel documents and much more.

Example query with authentication token...

const XLSX_DOC = '1SLFSDA93LD30AKD3L3098KFLZBODFMS3K';
const XLSX_SHEET = 'Sheet1';
const SHAREPOINT_URL = `https://graph.microsoft.com/v1.0/me/drive/items/${XLSX_DOC}/workbook/worksheets/${XLSX_SHEET}/usedRange`;

const accessToken = req.params.token;
const bearer = `Bearer ${accessToken}`;
let headers = new Headers();
headers.append("Authorization", bearer);
const options = {
    method: "GET",
    headers: headers
};
const response = await fetch(SHAREPOINT_URL, options);
const data = await response.json();
console.log(data); // Sharepoint excel data!

To get the sharepoint doc, you will need to go to the Microsoft graph explorer and input the query "https://graph.microsoft.com/v1.0/me/drive/root/children". This will return the list of sharepoint excel files you have, find the file such as "Book.xlsx", whatever the file name is, and copy the ID, done.

To get the sharepoint sheet, you just put the name of the sheet.

There is a lot more you can do once you get to this point. You can explore other things you can do in this wiki https://learn.microsoft.com/en-US/graph/api/overview?view=graph-rest-1.0. If you have any questions feel free to reply here or message me directly.