-
Notifications
You must be signed in to change notification settings - Fork 70
Cross Origin Resource Sharing (CORS)
In our application, we need to setup CORS so that we can control how browsers access resources on our server, as well as accessible HTTP response headers. It is a web security mechanism, and a requirement to be setup on the server if we want any web browser to access the CDS Services we set up. Since we are going to be testing with the CDS Hooks Sandbox web application, we need to implement CORS on the server-side end to allow the sandbox to make calls to our server.
Since our application is just a tutorial app, we can start by setting these following values:
app.use((request, response, next) => {
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
response.setHeader('Access-Control-Allow-Credentials', 'true');
response.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
response.setHeader('Access-Control-Expose-Headers', 'Origin, Accept, Content-Location, ' +
'Location, X-Requested-With');
// Pass to next layer of middleware
next();
});
CORS will be implemented in the application-level middleware of our application. And since it is middleware, we have access
to the request
object, the response
object, and a next
method to pass on to the next level of middleware. We will use the response
object to set our headers.
The important headers to set and note are the following:
-
Access-Control-Allow-Origin
- allow our server resources to be sent to any entity calling the CDS Services -
Access-Control-Allow-Methods
- for now, the only HTTP request methods that should hit our services are GET, POST, and OPTIONS -
Access-Control-Allow-Headers
- the Sandbox sends an Authorization header with each CDS service call it makes, so we must ensure that our server can take requests from entities that have this header in their CDS Service request.
When you are building your CDS Service for production, you'll want to carefully consider how you implement CORS as the configuration for this tutorial is trivial and likely too permissive for production use. A CORS configuration that meets your security policy and is within your risk tolerance is outside of the scope of this tutorial. There are many resources online that can help you understand CORS and determine how to configure it to fit your needs:
Next step: Trusting CDS Clients