Skip to content

Options for Access-Control-Allow-Origin in a Multitenant SaaS Environment

0

Hello AWS Community,

We operate a multitenant SaaS platform using CloudFront and S3 for storing our assets. To protect these assets, we utilize signed cookies. However, due to this setup, we cannot use * for the Access-Control-Allow-Origin header.

Some of our clients have their own domain names, while others do not, making it challenging to create a policy that includes *. What options are available to us in this situation?

The only solution I can think of is using a CloudFront function to dynamically construct the Access-Control-Allow-Origin policy based on the host. However, this approach appears similar to using *, as it effectively allows access from all domains. I'm also concerned about the potential costs associated with this solution, given the frequency of invocations.

Thank you for your assistance!

1 Answer
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

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.