Not able to connect to AWS S3 from React App - reactjs

EDIT
I've found out through the comments that I was querying the general S3 api instead of the specific buckets api. Doing that from a browser does not work and I got the error I reported here. In order to "fix" that, I simply switched to using the specific buckets API.
I used the same configurations, but instead I called the s3.upload method as in:
const uploadFile = (file) => {
const uploadParams = { ACL: "public-read", Bucket: config.bucketName, Key: file.name, Body: file };
s3.upload(uploadParams, function (err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data.Location);
// setProfilePic(data.location)
}
})
}
I want to upload a file to S3 from my React app. I am using the "official" aws-sdk module, from following this tutorial: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html#s3-example-creating-buckets-scenario
The problem is that I am getting a CORS error right in my first attempt to print my buckets:
import AWS from 'aws-sdk'
const config = {
bucketName: 'train-my-game',
dirName: 'profile', /* optional */
region: 'us-east-2',
accessKeyId: proccess.env.ACCESS_KEY,
secretAccessKey: proccess.env.SECRET,
}
AWS.config.update({ region: config.region, accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey });
const s3 = new AWS.S3({ apiVersion: '2006-03-01' });
const printBuckets = () => {
s3.listBuckets(function (err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data.Buckets);
}
});
}
printBuckets()
This fails with the error:
Access to XMLHttpRequest at 'https://s3.us-east-2.amazonaws.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
In the AWS, my bucket is configured with the following permission XML for the CORS configuration:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Does anyone know how to fix this?
Thank you

To put objects to a bucket, list objects in a bucket, retrieve bucket policies etc. you need to enable CORS on the target S3 bucket. Read the CORS documentation or see the example at awslabs/aws-js-s3-explorer.
You will not be able to invoke ListBuckets, however. The reason is that the ListBuckets call is made to an S3 service endpoint (s3.amazonzaws.com), not to an S3 bucket endpoint (bucket.s3.amazonaws.com) and you cannot enable CORS on the S3 service endpoint. So, ListBuckets will never work in a regular browser. Some browsers allow you to suppress CORS, but it's not normal browser operation. Obviously, if your app were to run outside of the browser, e.g. as a CLI or in Electron, then ListBuckets would work fine.

If you’d like to send Authorization headers, your server had better be configured to allow it. Set your server up so it responds to an OPTIONS request at that url with an Access-Control-Allow-Headers: Authorization header.

Cross-Origin-Resource-Sharing (CORS) is the mechanism that prevents a web app from running client-side code which makes requests to another web app. Imagine if Facebook could run some javascript and read the email you have in Gmail (because you're already logged in).
To address this, all browsers block javascript from one server from accessing any HTTP resources at any other url/ip unless that URL or IP explicitly allows (trusts) the site that javascript originate from.
In the case of many of the AWS SDK's you must explicitly configure what CORS headers you would like to send when interfacing with your AWS (S3 in this case) Resources.
See: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cors.html
Replace the AllowedOrigin "example.org" with the FQDN of the server serving your react application.

Related

Why React can't reach Flask endpoints in production?

I've got a React app with Flask on the backend in production and I found out
that none of my endpoints are reached from React.
I'm aware that when using client-side routing developer needs to use a catch-all function
similar to the below:
#app.errorhandler(404)
def error_handler(e):
return render_template('index.html')
I'm using Flask-CORS to handle cross origin requests:
within config.py:
class ProductionConfig:
CORS_HEADERS = 'Content-Type'
...
...
my blueprint:
CORS(auth_blueprint, resources={r'/*': {"origins": "https://example.com", "allow_headers": "*", "expose_headers": "*"}})
#auth_blueprint.route('/auth/login', methods=['POST'])
#cross_origin()
def login():
...
...
on the frondend I'm defining headers like this:
const headers = { "Access-Control-Allow-Origin": "*" };
const url = "https://example.com:5000/auth/login";
axios.post(url, data, headers).then(resp => { ... })
And I'm not getting any errors whatsoever. Server's logs are clean and the console only shows Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com:5000/auth/login. (Reason: CORS request did not succeed).
"Reason: CORS request did not succeed" means that the server didn't return anything.
The app renders fine however React (axios) can't reach my endpoints. Are there any gotchas I'm not aware of ? When request is sent I'm not even getting a status code in the network tab.
Thank you.
Screenshot of the network tab:
You need to change the connection protocol to http.

https associated to an insecure XMLHttpRequest endpoint

My website is hosted on a cloud run app : https://ap4-xxxxxxxx.a.run.app/.
This website is calling an API which is hosted here https://ap4-xxxxxxxx.a.run.app/api/undefined. But this request is blocked in my browser .
Error message :
Mixed Content: The page at 'https://ap4-xxxxxxxx.a.run.app/' was
loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://ap4-xxxxxxxx.a.run.app/api/undefined/'. This request has been
blocked; the content must be served over HTTPS.
The API https://ap4-xxxxxxxx.a.run.app/api/undefined is working perfectly on my browser or with postman. And the code requesting it explicitly mentionned https :
const request = https://ap4-xxxxxxxx.a.run.app/api/${variable};
axios.get(request)
.then(result => {
const PlaceList = result.data.map(
station => {
const isFavorite = PlaceId.includes(Place.number);
return { ...Place, isFavorite: isFavorite }
}
);
this.setState({
PlaceList: PlaceList,
isLoading: false
})
updateFavPlaceList(PlaceList);
})
I don't understand what's wrong here. Is my app making an http call instead of https ? I read here (Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint) that, some https are self signed. Is it the case of cloud run?
I've tried Cors, but it did not help.
Any observation or suggestion would be very much appreciated.
It seems you are indeed somewhere making an HTTP:// request in your frontend or make sure your app doesn't issue redirects to http://.
.app domains are in hardcoded HSTS list of your browser. If you type any .app domain, it will be requested as https:// .There's no way to access a .app domain over http:// in a modern browser, even with XHR.
So here is a quick fix. I forced my backend (flask) to generate https url.
Using the answer from here : Flask url_for generating http URL instead of https
class ReverseProxied(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
scheme = environ.get('HTTP_X_FORWARDED_PROTO')
environ['wsgi.url_scheme'] = 'https'
app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)
There might be a better way (maybe forcing the frontend to request https), so feel free to comment on this.

Access to XMLHttpRequest blocked by CORS Policy in ReactJS using Axios

I'm setting up stripe connect button in my React Component using Axios. I keep getting this error after redirection
Access to XMLHttpRequest at 'https://connect.stripe.com/oauth/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Thankyou.js:40 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
I get the code from the url and create a curl request using axios.Post. This is the code in my redirect URL
// Thankyou.js
export default class Thankyou extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const code = qs.parse(this.props.location.search, {
ignoreQueryPrefix: true
}).code;
const params = {
client_id: "*******************",
client_secret: "**********************",
grant_type: "authorization_code",
code: code
};
axios
.post(
"https://connect.stripe.com/oauth/token",
// apiBaseUrl,
{ params }
)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
console.log(code);
}
render() {
return (
<div>
<h2>Thank you for connecting with us!</h2>
</div>
);
}
}
There is nothing wrong with your code, but most likely the API endpoint the code trying to reach is not setup for JavaScript web app. CORS policy is set on the server-side and enforced primarily on the browser-side.
The best way to work around is to use Stripe's JavaScript solution such as Strip React Elements or Stripe.js.
A hacky way to get around CORS would be setting up Reverse proxy with solutions such as NGINX. For example, you can use the following nginx configuration:
server {
listen 8080;
server_name _;
location / {
proxy_pass http://your-web-app:2020/;
}
location /stripe/ {
proxy_pass https://connect.stripe.com/;
}
}
By doing so, all the API calls to Stripe.com could be through /stripe under your web app's URL. For example, calling http://yourapp/stripe/oauth/token would be same as calling https://connect.stripe.com/oauth/token
That being said, the second solution is hacky and Stripe may decide to block your reverse proxy server.
basically you need to talk to whoever is hosting this https://connect.stripe.com/oauth/token to enable CORS (Cross Origin Resource Sharing )
It is a security measure implemented by most standard browsers to stop unwanted requests to your backend
It's probably because Stripe doesn't provide JavaScript client so you either have to use your own server proxy or use something like "https://cors-anywhere.herokuapp.com/https://connect.stripe.com/oauth/token"
I hope this answer would be useful to new users:
This issue can be easily fixed by using an annotation in your spring boot rest controller class.
Something like below (also ref screenshot):
#CrossOrigin(origins = "http://localhost:4200")
Explicitly mention the react JS server URL that is causing this issue.
Now after adding above annotation (with your react JS server URL) the browser will allow the flow.
All the best.
Learn about CORS
Think about it, there is anything wrong with your axios.post request, it's successfully contacting the server. But there is one more thing to do before the server let you execute or manipulate it's files.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy.
So your cross-origin request and the server Cross-Origin Resource Sharing (CORS) have to match.
How do you solve it?
Depending on your server and the server side programming language your are implementing, you can configure the different parameters to handle your CORS.
For example, you can configure that the only allowed methods will be:
GET HEAD
So if someone try to axios.post to your server with a different method like POST, it will return an error like this:
Access to XMLHttpRequest at 'https://connect.stripe.com/oauth/token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Thankyou.js:40 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
Resources:
https://www.w3.org/TR/cors/
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
I would suggest reading through this site: https://stripe.com/docs/recipes/elements-react
It gives specific instructions straight from stripe on using their API with react. Good luck!

Access-Control-Allow-Origin Error Only on a Single Route, Only When Deployed to GAE

I'm using google app engine to host both my frontend and my api backend. I'm getting the following errors when I'm polling the "slicingdone" route on my backend:
bootstrap e65cef5bb029055e1719:2 GET
https://playloopsbackend-217106.appspot.com/playloops/slicingdone 502
send # bootstrap e65cef5bb029055e1719:2
/videotogifs:1 Access to XMLHttpRequest at
'https://playloopsbackend-217106.appspot.com/playloops/slicingdone'
from origin 'https://playloopsfrontend.appspot.com' has been blocked
by CORS policy: No 'Access-Control-Allow-Origin' header is present on
the requested resource.
I poll the slicingdone function to figure out when trimming of a video on my backend is finished. It works locally but is presenting the above errors when deployed to gcloud.
slicingdone function on my backend looks like this(Express):
slicingdone(req, res, next) {
if(slicingIsDone == true){
res.status(200).send('true');
slicingIsDone = false;
}else{
res.status(200).send('false');
}
}
*Every other route on my backend works fine even when deployed. I have similar functions on the backend that manipulate videos using ffmpeg in different ways. I have whitelisted my frontend url on my backend, so I'm not sure why I'm getting these CORs errors. I store the video results in google cloud storage--perhaps I need to add my backend url to google cloud CORS whitelist?
Any help is much appreciated! Thank you!

Enabling CORS in Azure Service Fabric Web Api

I have an angular app that sends an http request to my Service Fabric Web API (deployed on a Secure Service Fabric cluster) like so:
$scope.request_headers = {
"Content-Type": "application/xml; charset=utf-8",
"Access-Control-Allow-Origin":"*"
}
$http({
url: "Service_Fabric_web_api_url",
method: "GET",
headers:$scope.request_headers
}).
then(function (result) {
console.log(result);
});
I've also enabled CORS globally in my web api startup class like so:
HttpConfiguration config = new HttpConfiguration();
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
When I run my angular app locally and try sending the http request, I still get this error:
XMLHttpRequest cannot load Service_Fabric_web_api_url. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:xxxxx' is therefore not allowed access. The response had HTTP status code 500.
I'm able to access my service directly from my browser with the same url.
Also, the same http request works when I tried deploying my Web Api on an unsecure Service Fabric Cluster with the same lines added to the startup class to enable CORS.
Why is this happening even though I've enabled CORS globally in my Web API and particularly when its on a secure cluster?
In your Startup.cs class, do you have this line? :
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
There are also a couple NuGet packages associated with Cors:
<package id="Microsoft.AspNet.Cors" version="5.0.0" targetFramework="net45" />
<package id="Microsoft.Owin.Cors" version="3.0.1" targetFramework="net45" />
The CORS message is a red herring. If you look at the end of the error message you'll see this:
The response had HTTP status code 500.
Usually the response will include some detail about the error. I suggest using a tool like Fiddler with HTTPS decryption enabled so you can see the content of the response.

Resources