Voiced by Amazon Polly |
Overview
In today’s web applications, secure data uploads protect user data and system management. This blog will walk you through creating a React application that securely loads and stores data in an Amazon S3 bucket. We will highlight the importance of token authentication to ensure secure communication between React applications and servers.
Pioneers in Cloud Consulting & Migration Services
- Reduced infrastructural costs
- Accelerated application deployment
Introduction
React is a popular JavaScript library for building user interfaces, and Amazon S3, the powerful and massive storage provided by Amazon Web Services (AWS) storage services.
This server-side configuration helps securely generate URLs and tokens, thereby increasing the overall security of data interactions. Together, these technologies enable developers to use secure and efficient data loading and retrieval systems while adhering to best practices in web development and cloud computing.
Steps to Set Up the React App
Creating a New React App:
1 2 3 |
npx create-react-app react-s3-example cd react-s3-example |
Installing Dependencies:
1 |
npm install aws-sdk react-dropzone axios |
Configuring AWS Credentials: Ensure your AWS credentials are set up by configuring AWS CLI or manually updating ~/.aws/credentials.
Steps to Configure Amazon S3 Bucket
Create an Amazon S3 bucket:
- Sign in to the AWS Management Console.
- Go to Amazon S3 and click Create Bucket.
- Follow the steps, give a specific package name, and select a region.
Configuring CORS:
- Set up CORS on the container by adding the following CORS configuration XML:
1 2 3 4 5 6 7 8 9 |
<CORSConfiguration> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> |
React App Implementation
Building the React Component (App.js):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import React, { useState } from 'react'; import axios from 'axios'; import { Dropzone } from './Dropzone'; function App() { const [uploadedFiles, setUploadedFiles] = useState([]); const [token, setToken] = useState(''); const handleUpload = async (file) => { try { const signedUrlResponse = await axios.post('http://localhost:5000/generate-signed-url', { filename: file.name }); const { signedUrl } = signedUrlResponse.data; await axios.put(signedUrl, file, { headers: { 'Content-Type': file.type } }); setUploadedFiles([...uploadedFiles, file.name]); } catch (error) { console.error('Error uploading file:', error); } }; const handleTokenRequest = async () => { try { const tokenResponse = await axios.get('http://localhost:5000/generate-token'); const { token } = tokenResponse.data; setToken(token); } catch (error) { console.error('Error fetching token:', error); } }; return ( <div> <h1>React S3 Upload Example</h1> <button onClick={handleTokenRequest}>Generate Token</button> <Dropzone onUpload={handleUpload} /> <div> <h2>Uploaded Files:</h2> <ul> {uploadedFiles.map((file) => ( <li key={file}>{file}</li> ))} </ul> </div> </div> ); } export default App; |
Creating the Dropzone Component (Dropzone.js):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import React, { useCallback } from 'react'; import { useDropzone } from 'react-dropzone'; export const Dropzone = ({ onUpload }) => { const onDrop = useCallback( (acceptedFiles) => { acceptedFiles.forEach((file) => { onUpload(file); }); }, [onUpload] ); const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop }); return ( <div {...getRootProps()} style={dropzoneStyles}> <input {...getInputProps()} /> <p>{isDragActive ? 'Drop the files here ...' : 'Drag & drop some files here, or click to select files'}</p> </div> ); }; const dropzoneStyles = { border: '2px dashed #eeeeee', borderRadius: '4px', padding: '20px', textAlign: 'center', }; |
Server-side Implementation (Node.js/Express)
Installing Server-side Dependencies:
1 |
npm install express aws-sdk uuid |
Creating the Express Server (server.js):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
const express = require('express'); const aws = require('aws-sdk'); const uuid = require('uuid'); const app = express(); const PORT = process.env.PORT || 5000; app.use(express.json()); const s3 = new aws.S3({ accessKeyId: process.env.AWS_ACCESS_KEY, secretAccessKey: process.env.AWS_SECRET_KEY, region: process.env.AWS_REGION, }); app.post('/generate-signed-url', (req, res) => { const { filename } = req.body; const params = { Bucket: 'your-s3-bucket-name', Key: filename, ContentType: 'application/octet-stream', ACL: 'public-read', // Adjust permissions as needed }; s3.getSignedUrl('putObject', params, (err, url) => { if (err) { console.error('Error generating signed URL:', err); return res.status(500).json({ error: 'Failed to generate signed URL' }); } res.json({ signedUrl: url }); }); }); app.get('/generate-token', (req, res) => { const token = uuid.v4(); // Generate a secure token res.json({ token }); }); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); |
Security measures:
Protect access and keys:
- Ensure AWS access and keys are securely stored, preferably using changing media.
- Consider using an AWS IAM role with the minimum required permissions.
CORS Settings and Amazon S3 Bucket Permissions:
- Make sure you configure CORS on your Amazon S3 bucket to control which domains can access your bucket.
- Fine-tune Amazon S3 bucket permissions to limit access based on your application’s needs.
Security Considerations
Protect access and keys:
- Create AWS IAM roles with special permissions instead of root credentials.
- Review the rules and keys regularly.
CORS Configuration and S3 Bucket Permissions:
- Check and test your CORS configuration to ensure it only allows appropriate fields.
- Use the rule of least privilege when setting permissions on your Amazon S3 bucket.
Testing the Application
Start the React app: npm start
Start the server: node server.js
Open the React app in a browser (usually located at http://localhost:3000) and test the file upload functionality.
Conclusion
In this blog, we have built a React app that keeps data safe when uploading and storing it in an Amazon S3 bucket. The key to secure communication between the React app and the server is the token authentication policy. Beyond the technical stuff, we’ve looked into broader web security topics, like keeping access keys safe, setting up CORS correctly, and following security best practices. This guide doesn’t just give you steps to follow; it helps you understand how to make things more secure. With this knowledge, you’re not just finishing a project; you’re ready to lead the way in creating strong, safe, and scalable systems in the ever-changing world of new tech.
Drop a query if you have any questions regarding React App and we will get back to you quickly.
Making IT Networks Enterprise-ready – Cloud Management Services
- Accelerated cloud migration
- End-to-end view of the cloud environment
About CloudThat
CloudThat is a leading provider of Cloud Training and Consulting services with a global presence in India, the USA, Asia, Europe, and Africa. Specializing in AWS, Microsoft Azure, GCP, VMware, Databricks, and more, the company serves mid-market and enterprise clients, offering comprehensive expertise in Cloud Migration, Data Platforms, DevOps, IoT, AI/ML, and more.
CloudThat is recognized as a top-tier partner with AWS and Microsoft, including the prestigious ‘Think Big’ partner award from AWS and the Microsoft Superstars FY 2023 award in Asia & India. Having trained 650k+ professionals in 500+ cloud certifications and completed 300+ consulting projects globally, CloudThat is an official AWS Advanced Consulting Partner, AWS Training Partner, AWS Migration Partner, AWS Data and Analytics Partner, AWS DevOps Competency Partner, Amazon QuickSight Service Delivery Partner, Amazon EKS Service Delivery Partner, Microsoft Gold Partner, AWS Microsoft Workload Partners, Amazon EC2 Service Delivery Partner, and many more.
To get started, go through our Consultancy page and Managed Services Package, CloudThat’s offerings.
FAQs
1. Why is token authentication important in Amazon S3 archive upload?
ANS: – Token authentication adds an extra layer of security by ensuring that only authorized users interact with your servers and Amazon S3 buckets. It helps prevent unauthorized access and protect sensitive data.
2. How do I get AWS rights and keys for an Amazon S3 connection?
ANS: – You can get AWS access and keys with appropriate permissions by creating AWS IAM users. These keys should be stored securely and not shared publicly.
3. What is the purpose of CORS configuration in the Amazon S3 bucket?
ANS: – CORS configuration in the Amazon S3 bucket is important to control which domains are allowed to access the resources in the bucket. It increases security by preventing cross-border illegal practices.
WRITTEN BY Shreya Shah
Click to Comment