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.
Prerequisites
Before we dive into the technical details, ensure you have:
A Microsoft account with OneDrive
An application registered in Azure Portal for OneDrive API access
Node.js installed on your system
Install axios to make API calls to Microsoft’s Graph API
npm install axios
Step 1: Register a OneDrive App in Azure
To begin, you need to register an app in Azure to get the client ID and client secret for OAuth 2.0.
Go to the Azure Portal: Azure Portal
App Registration:
Navigate to Microsoft Entra ID > App Registrations > New Registration.
Set a name for the app and configure the supported account types.
Set your Redirect URI (e.g.,
http://localhost:3000
for local development).
3. API Permissions:
- Add Microsoft Graph Permissions for Files.ReadWrite.All and offline_access to enable full access to the OneDrive files.
4. Create a Client Secret:
- Go to Certificates & Secrets, generate a client secret, and store it securely. You’ll need this to generate access tokens.
Step 2: OAuth 2.0 Authentication Flow
Once you register your app in Azure, you can generate access and refresh tokens using the OAuth 2.0 flow.
- Use the Authorization URL to generate the first access and refresh tokens
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.
2. Exchange Authorization Code for Tokens: Use the following POST request to exchange the authorization code for access and refresh tokens
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
Step 3: Refresh Token Flow
Since OneDrive access tokens expire after 1 hour, you must refresh tokens to maintain long-term access. Here’s how you refresh the token:
- Use the refresh token to get a new access 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
Step 4: OneDrive File Upload via Graph API
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:
- PUT request for file upload
Request Body
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;
};
Step 5: Handling File Conflicts with ETags
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.
- Conflict Behavior
To replace a file, use the following request with conflict behavior handling:
PUT https://graph.microsoft.com/v1.0/me/drive/root:/YOUR_PATH:/content?conflictBehavior=replace
Step 6: Downloading Assets from OneDrive
- Fetch File Metadata
Before downloading a file, fetch its metadata for details like the filename, size, or URL.
- GET Request for File Metadata:
GET https://graph.microsoft.com/v1.0/me/drive/root:/YOUR_PATH:/content
- This request will return metadata for the file at YOUR_PATH.
Example Response:
{
"id": "file_id",
"name": "example.txt",
"size": 1024,
"createdDateTime": "2023-09-21T12:00:00Z",
"webUrl": "https://onedrive.live.com/..."
}
2. Download File Content
You’ll use the GET method, along with the file path, to download the actual file content and retrieve the file’s download URL or content.
- GET Request for File Download
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 (for files)
}
);
// 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);
}
};
🚀 Before You Go:
👏 Found this OneDrive + React guide helpful? Give it a like!
💬 Used OneDrive API before? Share your insights!
🔄 Know someone who needs this? Share the post!
🌟 Your support keeps us going!
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!