Cross origin request block - amazon-web-services

I am working on angular fronted project and using angular7 project.
I am using aws api as backend. Whenever I call the aws api its giving me
following errors.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxxxxx.execute-api.us-east-1.amazonaws.com/XXX/subscriptionpayment. (Reason: missing token ‘access-control-allow-origin’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxxxxx.execute-api.us-east-1.amazonaws.com/XXX/subscriptionpayment. (Reason: CORS request did not succeed).
I am using following code
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'
})
};
let makePaymentUrl = "https://xxxxx.execute-api.us-east-1.amazonaws.com/xxxx/subscriptionpayment";
return this.http.post(makePaymentUrl, params,httpOptions);

You need to enable CORS in the API gateway end point.
Follow : https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#how-to-cors-console

Where are you calling this request? if its a localhost maybe aws doesnt allow access to it. Check your API keys for this services
or double check your headers
try this

Related

Google OAuth CORS issue w/ flask-dance

I am setting up a flask-dance + flask-login project and am having issues with CORS. Specifically, I follow the standard flask-dance setup for Google OAuth:
google_blueprint = make_google_blueprint(
client_id=constants.GOOGLE_CLIENT_ID,
client_secret=constants.GOOGLE_CLIENT_SECRET,
scope=["profile", "email"]
)
app.register_blueprint(google_blueprint, url_prefix="/b/google_login")
On the frontend, I make a GET request to {backend}::/b/google_login/google, but get the following error:
Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=xxx&redirect_uri=http%3A%2F%2Flocalhost%3A5001%2Fb%2Fgoogle_login%2Fgoogle%2Fauthorized&scope=profile+email&state=xxx' (redirected from 'http://localhost:5001/b/google_login/google')
from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have added the redirect URI (i.e. /b/google_login/google/authorized to the redirect-URI whitelist). I am confused why this error is happening - as I am proxying the OAuth redirect through my server.
When I attempt the flow through window.href = http://localhost:5001/b/google_login/google - the flow works without issue.
Anyone have any idea why this is happening?

CORS Strict Origin using S3 Bucket and CloudFront

I'm using a S3 Bucket with a CloudFront distribution on a sub domain but I get strict-origin-when-cross-origin on a GET request. I can't see what I've done wrong so any help is greatly appreciated.
My website url is https://www.project1.tompenn.co.uk/
And my content url is https://content.tompenn.co.uk/TFTSet7_2/traits.json
Developer Console on my website is throwing the error: Access to fetch at 'https://content.tompenn.co.uk/TFTSet7/traits.json' from origin 'https://www.project1.tompenn.co.uk' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Here is the CORS policy on my S3 Bucket:
Here is how my CloudFront Distribution is setup. I only have the one behaviour and this is the config for it:
I had a very similar issue and after hours of banging my head against the wall I found that something with Chrome's HTTP caching mechanism prevents the Origin header from being sent. This is a Chrome-specific issue as I could not reproduce it with Safari. You can check whether this is the case for you as well by toggling the "Disable Cache" option under the Network tab of Chrome developer tools.
To force your request to ignore the cache, use appropriate cache option (documentation). This is my final working code:
fetch(url, {
method: 'GET',
mode: 'cors',
cache: 'no-store', // for some reason Chrome's caching doesn't send Origin
})
You can check your cloudfront and S3 configuration based on these links:
https://www.mslinn.com/blog/2021/03/21/cors-aws.html
https://aws.amazon.com/premiumsupport/knowledge-center/no-access-control-allow-origin-error/
Correct S3 + Cloudfront CORS Configuration?
Also, as Stephen pointed out, Chrome also has caching that may cause CORS, which can be addressed with:
fetch(myRequest, {
method: 'GET',
mode: 'cors',
cache: 'no-store',
})
Okay changing this option seems to have solved my issue.

Cannot query AWS API Gateway using API Key and CORs

I'm almost complete with a new web app, however, I'm getting a 403 error from AWS's API Gateway due to a CORs issue.
I'm creating a Vue app and using Vue's axios library. CORs is enabled and the request works with API Key Required option turned off in AWS's API Gateway by sending the following:
axios
.get('My-URL-Endpoint',{headers: {})
.then(response => (this.passports = response.data ));
When I turn on API Key Required functionality inside AWS's API Gateway. It works when I use Postman along with including x-api-key: My-API-Key. However, using Vue's axios it does not work and returns error 403:
axios
.get('My-URL-Endpoint', {headers: {
'x-api-key': 'My-API-Key'
}})
.then(response => (this.passports = response.data ));
My first instinct is that the problem is related to how Axios is sending the request through the browser. From what I can gather it looks like the pre-flight check is failing because I am receiving the following error within the browser:
Access to XMLHttpRequest at 'My-URL' from origin 'http://localhost:8080' 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.
Sure enough it looks like there is no access-control-allow-origin key in the response. So I added access-control-allow-origin to the response of the 403 message and got a new error "It does not have HTTP ok status"
I've been trying nearly everything to get this to work! I came across stackoverflow answer where it seems like the person was suggesting that API Key Required Key functionality can't work with CORs. This kind of seemed like that cannot be true. It would be a pretty crippling restriction.
So my question is how to get the browser's pre-flight check to work along with CORs and API Key capability inside AWS's API Gateway?
Thank you!
If you have enabled cors on your api gateway, the next place to look is the application code such as lambda. Make sure the Lambda is returning the correct cross origin headers in both successful and failure scenarios.
First of all you can check if the request is reaching the lambda from the cloud watch logs. Another way to check this is to temporarily point the Api gateway target to the Mock end point.
If the mock endpoint works, then the problem is the application code. otherwise the problem is in your api gateway end point.
Also note that any headers you use should be white listed in the Access-Control-Allow-headers section when you enable to cors for your method/resource.

CORS access error for PUT method, api on aws hosted on elastic beanstalk

I've deployed an api on AWS API Gateway using http custom integration
I've enabled CORS as seen below:
(source: upload.cat)
For both GET and PUT methods, I am getting the following error:
"url from origin [my origin] has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource"
Code:
fetch(url, {
method: 'POST',
mode: "cors",
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token' //copied from screenshot above
},
body: JSON.stringify(data)
})
.then(response => console.log('Success:', response))
.catch(error => console.error('Error:', error));
}
Access-Control-Allow-Headers are set in the server, you should remove it from your code. It won't make any difference if you put it in your request.
Is your API Gateway method protected by Lambda Authorizer or configured to use an API Key? If so, request might be rejected by one of them and response won't include Access-Control-Allow-Origin header so browser's preflight check will be failed.
You also need to check what response is being returned by API method integration. In case of Proxy Lambda, response should include Access-Control-Allow-Origin header.
Take a look at integration response documentation.

CORS error despite 'Access-Control-Allow-Origin' specified in Lambda response when using Lambda, API Gateway and Cloudfront

I have a deployed web app, it's built with a React & Redux frontend hosted on S3, and a several backend micro-services hosted on AWS Lambda and exposed over API Gateway that were deployed with Serverless. The site is also distributed via a CloudFront CDN.
The micro-services interact with several external services but the primary one I am concerned with is the get-products service which queries the Stripe product database and returns the products to my React app from there.
The site has been working fine until yesterday when I deployed some new (basically cosmetic) changes to front end, and added some more SKUs to the Stripe database. Since adding these changes I have started to experience CORS errors where previously there were none.
Initially I got the following error:
Access to XMLHttpRequest at 'https://XXXXXXXXXX.execute-api.eu-west-1.amazonaws.com/dev/products' from origin 'https://www.superfunwebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This was despite my Lambda response including the following headers:
'Access-Control-Allow-Origin': '*',
At this point I updated my Lambdas response headers to the following:
'Access-Control-Allow-Origin': 'https://www.superfunwebsite.com/',
'Access-Control-Allow-Credentials': true
The error has largely persisted, except for on one random page load where instead I got an error stating that the Origin https://www.superfunwebsite.com and 'Access-Control-Allow-Origin' https://www.superfunwebsite.com/ didn't match.
I've since changed the Lambda response headers to this:
'Access-Control-Allow-Origin': 'https://www.superfunwebsite.com',
'Access-Control-Allow-Credentials': true
Which seems as though it may have solved that anomalous second error.
However, error one persists even when I am testing using a HTTP client like Insomnia. I get the following in the response.
// status code
403
// response
{
"message": "Forbidden"
}
// headers
Content-Type: application/json
Content-Length: 23
Connection: keep-alive
Date: Tue, 18 Sep 2018 13:22:41 GMT
x-amzn-RequestId: eb691541-bb45-11e8-82ff-6d1b542dffb9
x-amzn-ErrorType: ForbiddenException
x-amz-apigw-id: NaxVLGJgjoEF5Fg=
X-Cache: Error from cloudfront
Via: 1.1 08037e15a3c6f503f39825efeb7f0210.cloudfront.net (CloudFront)
X-Amz-Cf-Id: cbNtb4xKWc48VPFon-Cl9y27KmXRVLIN5SWuYwNWlWsTXeaAXx3z-Q==
Based on the above Insomnia output it seems that my issue is somehow related to CloudFront although I don't understand exactly how. This other S/O post seems to indicate that there should be options for me in the CloudFront behaviours section that would allow me to whitelist headers for the response, however these options are not visible to me in the console, I've seen suggestions this is because the origin is on S3.
My question is simply if anyone knows how I can fix this issue or if there is something else I've not considered that I should be looking at?
Here you have to Whitelist the respective CORS headers in the behaviour section of the cloudfront distribution.
Open your distribution from the Amazon CloudFront console
Choose the Behaviors view.
Choose Create Behavior, or choose an existing behavior and then choose Edit.
For option Cache Based on Selected Request Headers, choose Whitelist.
Under Whitelist Headers, choose headers (Access-Control-Request-Headers and Access-Control-request-methods, Origin) from the menu on the left, and then choose Add.
Choose Yes, Edit.
The above settings should work for you (as its mainly for GET and HEAD) but if it doesn't, enable OPTIONS method as well using below article.
Please check the below article from aws:
no-access-control-allow-origin-error
Custom CORS Cloudfront
enhanced-cloudfront-customization
This issue has now been solved. In the end it was not in fact a CORS issue but a staging one. My query was failing because I was querying an endpoint stage that did not exist.
It appears that in the set up I had using CloudFront and API Gateway, when querying an endpoint that didn't exist I was returned a 403 response without CORS headers.
The browser/CloudFront (not sure which) then identified the absence of CORS headers and threw an error in response to that.
In my case simply changing my endpoint from the dev stage (which did not exist on the associated AWS account associated with the live stage):
https://XXXXXXXXXX.execute-api.eu-west-1.amazonaws.com/dev/products
To the live stage:
https://XXXXXXXXXX.execute-api.eu-west-1.amazonaws.com/live/products
Resolved the issue immediately.