Building a Blogging Site with React and PHP: A Step-by-Step Guide
In this post, I’ll share how to integrate Microsoft OneDrive with your React application.
We’ll explore the steps for OAuth 2.0 authentication, getting access and refresh tokens, managing file uploads, and addressing challenges like ETag conflicts and CORS issues.
Before we dive into the technical details, ensure you have:
npm install axios
To begin, you need to register an app in Azure to get the client ID and client secret for OAuth 2.0.
http://localhost:3000 for local development).Once you register your app in Azure, you can generate access and refresh tokens using the OAuth 2.0 flow.
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=YOUR_CLIENT_ID&
response_type=code&
redirect_uri=YOUR_REDIRECT_URI&
scope=openid profile Files.ReadWrite.All offline_access
Replace YOUR_CLIENT_ID and YOUR_REDIRECT_URI with your values. Once the user signs in, the system will provide an authorization code.
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Request Body:
client_id=YOUR_CLIENT_ID
client_secret=YOUR_CLIENT_SECRET
code=AUTHORIZATION_CODE
redirect_uri=YOUR_REDIRECT_URI
grant_type=authorization_code
scope=Files.ReadWrite.All offline_access
REACT_APP_ONEDRIVE_ACCESS_TOKEN=your_onedrive_access_token
REACT_APP_ONEDRIVE_REFRESH_TOKEN=your_onedrive_refresh_token
Since OneDrive access tokens expire after 1 hour, you must refresh tokens to maintain long-term access. Here’s how you refresh the token:
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
Request Body:
client_id=YOUR_CLIENT_ID
client_secret=YOUR_CLIENT_SECRET
refresh_token=YOUR_REFRESH_TOKEN
redirect_uri=YOUR_REDIRECT_URI
grant_type=refresh_token
scope=Files.ReadWrite.All offline_access
With OneDrive authentication set up, we can now upload files to OneDrive. Below is an example of how to upload files via the Graph API:
Send the file data as binary content in the body and pass the access token in the header.
const uploadFileToOneDrive = async (path, fileContent) => {
const response = await axios.put(
`https://graph.microsoft.com/v1.0/me/drive/root:${path}:/content`,
fileContent,
{
headers: {
Authorization: `Bearer ${process.env.REACT_APP_ONEDRIVE_ACCESS_TOKEN}`,
'Content-Type': 'application/octet-stream',
},
}
);
return response.data;
};
OneDrive uses ETags to manage file versions, and you may encounter conflicts during file updates of the same file. To replace files, you need to handle ETag conflicts properly.
PUT https://graph.microsoft.com/v1.0/me/drive/root:/YOUR_PATH:/content?conflictBehavior=replace
GET https://graph.microsoft.com/v1.0/me/drive/root:/YOUR_PATH:/content?conflictBehavior=replace
{
"id": "file_id",
"name": "example.txt",
"size": 1024,
"createdDateTime": "2023-09-21T12:00:00Z",
"webUrl": "https://onedrive.live.com/..."
}
GET https://graph.microsoft.com/v1.0/me/drive/root:/YOUR_PATH:/content
You can download the file by making an API call to the Graph API endpoint:
const downloadAssetFromOneDrive = async (path) => {
try {
const response = await axios.get(
`https://graph.microsoft.com/v1.0/me/drive/root:${path}:/content`,
{
headers: {
Authorization: `Bearer ${process.env.REACT_APP_ONEDRIVE_ACCESS_TOKEN}`,
},
responseType: 'blob', // Ensures the response is treated as binary data
}
);
// Create a URL for the blob to allow download
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
// Extract the filename from the path
const fileName = path.split('/').pop();
link.setAttribute('download', fileName); // Set the download attribute with the file name
// Append link to the document and simulate click for download
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
console.log("File downloaded successfully");
} catch (error) {
console.error("Error downloading the file from OneDrive", error);
}
};
💻 Level up with the latest tech trends, tutorials, and tips - Straight to your inbox – no fluff, just value!
Your email address will not be published. Required fields are marked *
Note: Some links on this page might be affiliate links. If you make a purchase through these links, I may earn a small commission at no extra cost to you. Thanks for your support!
Comments (2)