CloudFront Distribution for route53 domain

28 Views Asked by At

I'm trying to create an AWS Clountfront distribution that will be redirected to 2 different load balancers. The requirement is to create a CloudFront function that does a redirect based on the Authorization header content.

The function code works fine and does the redirection based on the content. However, I can't forward the Authorization header after the redirect. After the function being executed Cloudfront removes the Header, there are a bunch of explanations saying that I should create a Cache configuration that allows passing Authorization header, but my configurations don't work, I already tried configuring the cache and also used legacy cache.

That's my current configuration with Cache disabled and asking to Foward AllHeaders: enter image description here

So basically my function code is:

    function handler(event) {
    var request = event.request;
    var headers = request.headers;
    var originalPath = request.uri;
    // Check if Authorization header starts with "Bearer "
    var authorizationHeader = headers["authorization"] ? headers["authorization"].value : null;

    if (authorizationHeader && authorizationHeader.startsWith("Bearer ")) {
        // Check if total size is between 39 and 41 characters
        var headerSize = authorizationHeader.length;
        if (headerSize >= 39 && headerSize <= 41) {
            // Redirect to hostv1 with original path appended and preserve original headers
            return redirectTo("${hostv1}", originalPath, headers);
        }
    }
    // Check if Authorization header is not present
    if (!authorizationHeader) {
        // Redirect to hostv1 with original path appended and preserve original headers
        return redirectTo("${hostv1}", originalPath, headers);
    }

    // Authorization header is present, but conditions are not met, redirect to hostv2 with original path appended and preserve original headers
    return redirectTo("${hostv2}", originalPath, headers);
}

// Define a helper function for redirection
function redirectTo(destination, originalPath, headers) {
    // Create response headers with the provided destination URL and original headers
    var responseHeaders = Object.assign(
        { "location": { "value": destination + originalPath } },
        headers  // Include all original headers
    );
    delete responseHeaders['host']; // Remove the 'host' header if present
    // Return the redirection response
    return {
        statusCode: 302,
        statusDescription: 'Found',
        headers: responseHeaders
    };
}

If someone already had success on that, please let me know.

0

There are 0 best solutions below