1 Answer
- Newest
- Most votes
- Most comments
0
As you mentioned, you can use a CloudFront function to dynamically set the Access-Control-Allow-Origin header based on the request's Origin. This allows you to return the correct origin for each tenant, while avoiding the use of *.
Here’s how this can be done with CloudFront Functions:
function handler(event) {
var request = event.request;
var headers = request.headers;
var origin = headers['origin'] ? headers['origin'].value : '';
// A list of allowed tenant domains (this could be dynamically fetched from a database or another source)
var allowedOrigins = [
'https://client1.example.com',
'https://client2.example.com',
// add other tenant domains here
];
// If the origin is in the allowedOrigins list, set the Access-Control-Allow-Origin header
if (allowedOrigins.includes(origin)) {
var response = event.response || {};
var responseHeaders = response.headers || {};
responseHeaders['access-control-allow-origin'] = [{ key: 'Access-Control-Allow-Origin', value: origin }];
response.headers = responseHeaders;
return response;
}
// If not an allowed origin, return a response with a 403 Forbidden status
return {
statusCode: 403,
statusDescription: 'Forbidden',
body: 'Access forbidden: CORS violation'
};
}
answered 2 years ago
Relevant content
asked 3 years ago
asked 2 years ago
asked 3 years ago
asked 3 years ago
