Encountering a CORS error specifically when adding an Auth0 token to the request on the API gateway

I'm currently working on hosting a full stack web application in AWS. The setup involves an Angular frontend stored in an S3 bucket behind CloudFront, using a domain from Route53. On the backend, there's a TypeScript Express project behind API Gateway. For authentication, I'm utilizing Auth0 and their sample frontend/backend apps available on their website. You can find them here: https://github.com/auth0-developer-hub/spa_angular_typescript_hello-world https://github.com/auth0-developer-hub/api_express_typescript_hello-world

When making requests that bypass the interceptor, everything works fine. But when attempting requests modified by the interceptor (such as after logging in with Auth0), I encounter the following error message: "Access to XMLHttpRequest at 'https://api-gateway.com/dev/api/messages/protected' from origin 'https://website.link' 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."

Here is the interceptor code in the auth.module:

[Interceptor code snippet]

Additionally, below is my index.ts file from the Express backend, where I explicitly allow the "Authorization" header that the interceptor attaches. I've validated the tokens being passed as well.

[Express backend code snippet]

I've tried various solutions like setting the 'Access-Control-AllowOrigin' header on routes but haven't had success, examples of which are provided below:

[Sample code snippets showing attempted configurations]

All these attempts resulted in the same CORS policy error.

Edit: Including my CloudFront configuration using Terraform below:

[CloudFront configuration code snippet]

Answer №1

To resolve the problem, I implemented CORS for my resource within API Gateway and specifically permitted the "Authorization" header.

Answer №2

If you want to utilize API Gateway through Cloudfront by using the URL

https://cloudfront-host/api/endpoint
, you will need to set up a custom origin instead of relying on S3 as the origin server.

The reason why direct access is blocked when going through Cloudfront, while it works fine with Postman or Api Gateway alone, is due to Cloudfront acting as a gatekeeper for the requests. To make this setup work, you must configure ordered_cache_behavior so that Cloudfront can properly proxy requests to your custom API Gateway origin. Think of it as setting up a similar routing mechanism like proxy.conf.json in Angular, where all API endpoints following the pattern /api/<endpoint> will be routed to /api/* which leads to the API Gateway.

When defining the new origin, make sure to use custom_origin_config instead of s3_origin_config. Take some time to understand and adjust the settings of ordered_cache_behavior accordingly.

resource "aws_cloudfront_distribution" "website_distribution" {
  origin {
    domain_name = aws_s3_bucket.frontend_bucket.bucket_regional_domain_name
    origin_id   = aws_s3_bucket.frontend_bucket.id

    s3_origin_config {
      origin_access_identity = aws_cloudfront_origin_access_identity.oai.cloudfront_access_identity_path
    }
  }

  origin {
    domain_name = <>
    origin_id   = <some_id>

    custom_origin_config {
      ...
    }
  }

  ordered_cache_behavior {
    path_pattern     = "/api/*"
    ...
    target_origin_id = <some_id>
    ...
  }

...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2 form validation allowing submission to continue despite tag errors

Here is the code snippet provided: <form #theForm="ngForm" novalidate> <div *ngIf="pickUpAddress.cannotVerify"> <div class="form-group"> <sh-manual-address [(ngModel)]="pickUpAddress" #manualAddress="ngModel" [address]="pickU ...

Accessing Promise.all in the rejection function is not allowed

I have a service that retrieves data, and I make 5 calls to it with different parameters to retrieve various datasets. When the function is successful, everything works fine. However, in case of failure for any of the 5 calls, I need to handle it differen ...

What is the best way to dynamically add fields to every object in an array of Firestore documents using RxJS?

Trying to solve a challenging RxJS issue here. In my Angular service class, I initially had a method that fetched data from the Firebase Firestore database like this: async getAllEmployees() { return <Observable<User[]>> this.firestore.co ...

Learn how to subscribe to Azure Event Grid using Angular without the need for a backend service layer

I am currently working on an Angular project and I am looking to set up Azure Event Grid subscription directly from the client-side without the need for a backend service. After exploring different options, I have not yet found a straightforward solution. ...

Performing bulk operations on all selected rows in a table using Angular 6

Within my Angular 6 web application, there is a table with checkboxes in each row. My goal is to be able to perform bulk actions on the selected rows, such as deleting them. One approach I considered was adding an isSelected boolean property to the data m ...

Combining the values of two input fields in Angular

Within my form, I have three input fields labeled Name, hours, and minutes. When I execute a POST operation, I combine the values of hours and minutes into a variable named duration before sending it to the api. The resulting JSON structure appears as fo ...

Exploring the attributes and functions of JavaScript Objects in an Angular environment

Can Angular's $http.post method recognize JavaScript object properties when sending data? To understand more about JavaScript objects and their properties, visit https://www.w3schools.com/js/js_objects.asp. Here is an example to illustrate my questio ...

Angular2 filter array of objects

I am struggling to effectively filter through an array of objects. Can someone point out what I might be doing incorrectly? My Filter Pipe transform(value: any, args?: any): any { if (!args) return value; return value.filter(item => this.che ...

Mongoose failing to persist subdocument

After trying to insert into my collection, I noticed that the sub-document is not being saved along with it. This issue has left me puzzled. This is the scheme/model I am working with: import { Schema, Document, Model, model } from 'mongoose' ...

A guide on transferring files between shared and other folders using Angular 2

In my shared folder, I created a subfolder named activities. Within this activities folder, I included HTML and CSS files to be fetched by another folder called User. However, I encountered an error: ERROR Error: Uncaught (in promise): Error: Cannot fin ...

`Two side-by-side nvd3 visualizations`

I am seeking assistance with arranging two nvd3 graphs side by side on a webpage. Below is the code I am currently using: <div class="container" > <!-- Graph 1--> <div class="rows"> <nvd3 [options]="optionsGraph1" [data]="Gra ...

Verify an entry with exactly 7 numerical digits

When inputting data, the user is limited to entering only 7 figures. If more than 7 figures are entered, an error message will display: "You need 7 digits". For instance, if the user enters something like this: 12345678910 The error message is correctly ...

Can we combine two arrays of objects based on their unique identifiers?

I am working with two arrays of objects: firstAry = [{ "status": "Creating", "datacenter-id": "1test", "datacenter-name": "1name" }, { "status": "Creating", ...

One endeavor, countless customers. Angular 2

I have a burning question that I can't seem to find the answer to. Imagine I have a project called x, meant for multiple clients, each with their own unique functionalities, style sheets, and HTML layouts. Some of these functionalities may be shared, ...

Angular trailing zero problem

There is a function that returns a number. Within this function, a string '1.10' is present, which is then converted to a number using the Number method. The output obtained is 1.1, but the desired output is 1.10. I have tried using methods lik ...

You are unable to define a module within an NgModule since it is not included in the current Angular compilation

Something strange is happening here as I am encountering an error message stating 'Cannot declare 'FormsModule' in an NgModule as it's not a part of the current compilation' when trying to import 'FormsModule' and 'R ...

Enforcement of Typescript Field Type Lax During Assignment

My current issue involves a constructor that is supposed to set the value of _device. The field is specifically designed to be of type number, and the constructor parameter is also expected to be of type number. However, when a parameter of type string is ...

Avoid redundant GET requests in your Angular application initialization by utilizing RxJS

Is there a way to consolidate multiple http requests into one in Angular or RxJS, if they are triggered closely together? For instance, when I open my application, all 20 components call the same http request in their ngOnInit method: https://i.sstatic.n ...

Error: Cannot read property 'map' of undefined in React-Native

I am attempting to display a series of icons from an array called icons. However, when I try to use {icons.map((icon, index) =>(<Icon key = {index} icon={icon}/>)}, I encounter the error message "typeError: undefined is not an object (evaluating & ...

Is it more efficient to wait for the server to respond, or should I update the client immediately

Today, I found myself contemplating an interesting question. As I work on developing a Single Page Application (SPA) using Angular, I am focusing on creating a calendar module similar to Google Calendar. This module will allow users to add, edit, and remov ...