How to stop 'CORS missing allow origin error' when deploying Express application using Serverless Component? - express

When my React frontend calls my Typescript Express REST API (hosted on API Gateway using Serverless Components), I get the following error:
Access to XMLHttpRequest at 'https://randomId.execute-api.ap-southeast-2.amazonaws.com/userLoginSignup' from origin 'https://www.tueshey.com' 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.
My app.ts CORS config is like this (for reference, here's my whole file):
...
const app = express();
// CORS
const allowlist = ['https://www.tueshey.com'];
const options: cors.CorsOptions = {
origin: allowlist,
};
app.use(cors(options));
...
When I inspect the request locally, there is an OPTIONS request that returns first that includes the Allow Access Origin header but not when I deploy it. It is working correctly locally.

you will have to enable CORS on API Gateway as well. When click on the resource endpoint on API Gateway, on actions there is Enable CORS. That will add Options method also for your resource. If you want some customization you will have to add OPTIONS method manually

Related

Access to fetch at * from origin * has been blocked by CORS policy, even though CORS policy explicitly allows it

I am performing a graphql query from my client to my server and am getting the following error in the browser:
Access to fetch at 'https://my-server.com/graphql' from origin 'https://my-client.com' 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.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I once got this same error in the past which is why I added the following to the express middleware on the server which solved it:
const app = express();
app.use(cors({
origin: ['http://localhost:3000', 'https://studio.apollographql.com', "https://my-client.com"],
credentials: true
}))
However without any changes that I can reasonably trace back to this issue the error is occurring again. The strange thing if I run the client and server on my local machine (on localhost:3000 and localhost:4000 respectively) the error does not happen.
Edit:
On the client I use a library called GraphQL Code Generator to generate hooks which execute the relevant queries. One of them is for instance this one:
export function useUsersQuery(baseOptions?: Apollo.QueryHookOptions<UsersQuery, UsersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<UsersQuery, UsersQueryVariables>(UsersDocument, options);
}
And to execute the query: const { data, loading, error } = useUsersQuery()
I am using the following package versions
apollo-server-express#3.11.1
express#4.18.2
cors#2.8.5

Manage CORS between Google App Engine & Google Cloud Function

I'm trying to set up a new instance of a simple App Engine which communicate with a backend-function hosted on Google Cloud Function. The App Engine is protected with IAP, and the Google Cloud Function is private only. The GAE use Angular Framework and GCF use Node 14 with Express
.
I can't access to my GCF from the App Engine because the requests are blocked by CORS.
Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I tried the popular solutions on the web :
Use the cors librairie on the GCF. So I had on my GCF
var cors = require('cors')
app.use(cors(cors({ credentials: true, origin: true })))
And I also add this line for every request
res.set('Access-Control-Allow-Origin', '*')
Add the http-header on my app.yaml
handlers:
- url: /(.*\.[A-Za-z0-9]{1,4})$
static_files: dist/\1
upload: dist/(.*\.[A-Za-z0-9]{1,4})$
http_headers:
Access-Control-Allow-Origin: "*"
- url: /(.*)$
static_files: dist/index.html
upload: dist/index.html
http_headers:
Access-Control-Allow-Origin: "*"
But I still get the same error message.
EDIT : so the first problem was due to an authentication issue, that why the error have the same response. So I decided to deploy the 2 apps on App Engine to simplify communication between the 2 services.
You can now have full access to the HTTP Request/Responses by setting
the appropriate CORS headers as per this documentation.
Just so you know the reason for the error you are facing, it is
because when your web browser is calling a service that is in a
different/cross domain, it doesn’t make a HTTP request right away, it
rather starts with making an OPTIONS request( a preflight request)
and compares the value of Access-Control-Allow-Origin header in the
result with the current domain i.e. it checks for this (req.method
=== 'OPTIONS') in the headers and if the header value matches the host, the actual call is made, otherwise the action is stopped and
the error as the one above is thrown.
To have a thorough understanding of the above concept, have a look at
this stackoverflow answer and read this article for more insights.

Docusign - Axios CORS (Working on Postman)

I'm trying to make this API call from my vue.js SPA.
this.$apiCallDocusign.post('/oauth/token', {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: '{myJWT}'
})
$apiCallDocusign is:
import axios from 'axios'
var h_ds = {}
h_ds = {
"Content-Type": "application/json"
}
const apiUrlDocusign = 'https://account-d.docusign.com'
const apiCallDocusign = axios.create({
baseURL: apiUrlDocusign,
headers: h_ds
})
export default apiCallDocusign
But i get CORS error:
Access to XMLHttpRequest at 'https://account-d.docusign.com/oauth/token' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
It works in Postman or Terminal with curl... Thanks in advance
Several issues here:
The only OAuth flow that may be used from a SPA to DocuSign is the Implicit grant flow. It works fine from a SPA (I use it myself.) JWT grant can't be used since there is no way to protect the needed private key from others.
An alternative is to have a lightweight server app that generates a DocuSign Access Token by using the JWT grant and then returns it to your SPA. Be careful to secure the server app against bad guys.
You will also need to create a private CORS gateway for use by your application since DocuSign doesn't yet support CORS. Docs for creating a private CORS gateway.
To help raise the profile of CORS, please ask your DocuSign contacts
to add your name/organization to internal ticket PORTFOLIO-1100.
CORS is on our roadmap but is not yet scheduled.

CORS policy blocking POST requests to API

I'm trying to deploy an app I created online. The UI is created using vue.js and it's calling a API written in dotnet core. I'm running dotnet core 2.2.
The web project and the API are on different servers and accessible under different domains, the web project is hosted on Netlify if that makes a difference. I managed to set up the CORS policy so that locally everything worked fine. When I access the app on the webserver I receive CORS errors whenever I post data. My GET and DELETE requests work just fine.
Here is my CORS policy
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("Default", builder =>
{
builder.WithOrigins(/* the domain where my web project is hosted */);
builder.AllowAnyMethod();
builder.AllowAnyHeader();
builder.AllowCredentials();
});
});
}
So I'm thinking everything should be fine. AllowCredentials is required because I'm using SignalR which otherwise wouldn't work.
The error message in the dev tools is
POST [my api endpoint] 400 (Bad Request)
Access to XMLHttpRequest at '[my api endpoint]' from origin 'https://xxx.netlify.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And when I look into the console where my dotnet project is running I see the following error message
Connection id "0HLQNTR19GE1T" bad request data: "Requests with 'Connection: Upgrade' cannot have content in the request body."
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Requests with 'Connection: Upgrade' cannot have content in the request body.
at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1MessageBody.For(HttpVersion httpVersion, HttpRequestHeaders headers, Http1Connection context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection.CreateMessageBody()
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication`1 application)
So far I tried setting the Access-Control-Allow-Origin = "*" Header via the netlify.toml file, using the [EnableCors] attribute on my controller action. I edited my AJAX request (axios) and set withCredentials: true and in general played around with the CORS policy a lot. Unfortunately without luck and I'm running out of ideas.
I'm happy about any suggestions.
Check your nginx.conf file for a line called proxy_set_header and set it to Connection $http_connection

Implementing Okta in React Native and get: Response to preflight request doesn't pass access

I'm implementing the Okta signin widget with React Native
I get this:
Failed to load https://dev-827074.oktapreview.com/api/v1/sessions/me: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
After trying to login, I get the following:
UnsupportedBrowserError {name: "UNSUPPORTED_BROWSER_ERROR", message: "There was an error sending the request - have you enabled CORS?"}
We've received similar errors from Okta. What we had to do is add the hostname for the server that hosts the webview as a Trusted Origin.
API -> Trusted Origins -> Add Origin
You can add multiple origins, you probably need to add http://localhost:3000.
You may need to add http://localhost:3000/implicit/callback to your app's Login Redirect URI's in the General Settings of your Okta app
The API you have written does not support CORS. CORS or Cross origin resource sharing allows a web app to submit requests to an API belonging to a different domain. This setting should be enabled on the API side.
This is how it works, whenever a request is sent to a different domain, an OPTIONS method is sent to the server. The server responds back with available options for the web app. If the verb is supported, the browser will send the actual request with the appropriate verb or method (For example, GET or POST). If the verb is not supported, you get the above error message.
In short, enable CORS for your API. If it is a Node / Express API it is just a simple cors package you need to add to your project and use.