It shows how to escape cross-origin issues for web client and API server using CloudFront routing.

Overview

AWS CloudFront의 URL Routing을 이용한 Web Client 및 API Server 구현

여기서는 CliendFront의 URL Routing을 이용하여 Web Client와 API Server를 구현하고자 합니다. Web Client는 Amazon S3에 html과 javascript과 같은 respource들로 구성되며, javascript에서 '/status'와 같은 API를 호출하면, Amazon API Gateway를 통해 lambda를 호출하는 구조를 되어 있습니다. 또한, 쉽고 편리하게 인프라를 구축하기 위하여 AWS CDK를 이용합니다.

전체적인 Architecture는 아래와 같습니다. 사용자가 Amazon CloudFront를 이용해 web page에 접속 할 수 있습니다. 또한 restful api로 접속시에는 api의 method 이름을 이용하여 적절한 경로로 Routing 할 수 있습니다. 여기에서는 status Method를 가지고 '/status'라는 URL을 가지므로, Amazon API Gateway로 routing 되어지는데, 이때 API Gateway와 연결된 Lambda를 통해 원하는 동작을 요청 할 수 있습니다.

image

CORS 에러

브라우저는 HTTP 보안을 위해 리소스의 origin (domain, scheme, port)을 확인하여 원래 사이트의 origin과 다른 경우(cross-origin)에 접속을 제한합니다.

image

자신의 origin과 다른 리소스를 허용하려면 Cross-Origin Resource Sharing(CORS)를 적용하여야 하는데, 브라우저는 preflight request(OPTIONS)를 보내서 서버로부터 "approval"을 받으면, actual request를 보낼 수 있습니다. 여기서 OPTIONS 해더에 origin 헤더가 반드시 포함되어야 합니다.

noname

그런데, Chrome과 같은 브라우저에서 request에 origin을 허용하지 않은 경우가 있어서, API Gateway에서 CORS 설정을 하더라도, CORS 에러로 request가 실패 할 수 있습니다.

따라서, 여기에서는 원천적으로 crosss-origin 이슈가 발생하지 않도록, contents(html, css, js)와 같은 리소스가 같은 origin을 사용할 수 있도록 CloudFront를 사용하는 방법을 설명합니다.

CloudFront를 이용한 cross-origin 이슈 해결 방법

아래와 같이 CloudFront를 이용하여 '/status'로 시작하는 모든 request는 API Gateway를 통해 제공하고, 나머지 request는 S3로 routing 되도록 할 수 있습니다. 상세한 것은 CDK Cloudfront를 참고 하시기 바랍니다.

    const distribution = new cloudFront.Distribution(this, 'cloudfront', {
      defaultBehavior: {
        origin: new origins.S3Origin(s3Bucket),
        allowedMethods: cloudFront.AllowedMethods.ALLOW_ALL,
        cachePolicy: cloudFront.CachePolicy.CACHING_DISABLED,
        viewerProtocolPolicy: cloudFront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
      },
      priceClass: cloudFront.PriceClass.PRICE_CLASS_200,  
    });
    distribution.addBehavior("/status", new origins.RestApiOrigin(apigw), {
      cachePolicy: cloudFront.CachePolicy.CACHING_DISABLED,
      originRequestPolicy: myOriginRequestPolicy,
      viewerProtocolPolicy: cloudFront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
    });     

이렇게 할 경우에 아래와 같이 CloudFront에는 2개의 origin이 등록이 되는데, '/status' API의 경우는 api gateway로 전달되어 처리되고, 나머지는 S3로 라우팅 됩니다.

noname

CDK로 인프라 설치하기

git repository에서 소스를 다운로드 합니다.

$ git clone https://github.com/kyopark2014/aws-routable-cloudfront

아래의 AWS CDK명령어를 이용하여 인프라를 생성합니다.

$ cd cdk-cloudfront
$ cd cdk synth
$ cd deploy

인프라를 생성하는 방법은 AWS CDK 인프라 생성하기에서 상세히 설명하고 있습니다.

인프라 삭제시는 아래 명령어를 사용합니다.

$ cdk destroy

실행 결과

Postman에서 '/status' API 호출시

'/status'는 lambda-for-status로 routing되고 있으므로 아래와 같이 Lambda가 실행되는 것을 확인 할 수 있습니다.

noname

브라우저(Chrome)에서 "status.html"을 호출시

html 내부의 request.js가 실행되면서, '/status' API를 호출하게 됩니다.

  • "status.html"을 로딩 후 아래와 같이 [RUN]을 선택합니다. 여기서 "status.html"은 S3에 저장되어 있고, CloudFront를 통해 로딩됩니다.

image

  • [RUN] 버튼을 선택하면 "status.html"에서 지정한 "request.js"가 실행되는데, 이때 "lambda-for-status"를 호출하여 응답을 받고, 이것을 아래와 같이 화면에 "response"로 표시하고 있습니다.

image

Reference

AWS CDK — A Beginner’s Guide with Examples

aws-cdk-changelogs-demo

CloudFront to S3 and API Gateway

CORS란 무엇인가?

Cross-Origin Resource Sharing (CORS)

You might also like...

In this project we made a Tv shows webpage where you can like or comment the different shows.

In this project we made a Tv shows webpage where you can like or comment the different shows.

JS Capstone Project In this project we made a Tv shows webpage where you can like or comment the differents shows. Built With HTML CSS JavaScript Lint

Mar 16, 2022

A discord bot that generates Discord Nitro, Hulu accounts, Origin, spotify and VPNs!

A discord bot that generates Discord Nitro, Hulu accounts, Origin, spotify and VPNs!

Discord-Account-Generator-Bot A discord bot that generates Discord Nitro, Hulu accounts, Origin, spotify and VPNs! Tutorial Basically download the fil

Oct 4, 2022

Avoid CORS issues by using API Routes from Next.js

CORS Demo Avoid CORS issues by using API Routes from Next.js. Get Started Clone the repo git clone [email protected]:gregrickaby/cors-demo.git CD into co

Sep 30, 2022

Labels issues using OpenAI's Classification API powered by GPT-3 models!

Labels issues using OpenAI's Classification API powered by GPT-3 models!

OpenAI Issue Labeler 🤖 This GitHub action labels issues using OpenAI's Classification API powered by GPT-3 models! We are using curie as our completi

Dec 21, 2022

EA Origin platform username checker

Origin EA Origin platform username checker. Instructions [?] Installation "npm i" [?] Fill in your Discord webhook details. "var webhookId = ``;" "va

Sep 29, 2022

Demo showcasing information leaks resulting from an IndexedDB same-origin policy violation in WebKit.

Safari 15 IndexedDB Leaks Description This demo showcases information leaks resulting from an IndexedDB same-origin policy violation in WebKit (a brow

Nov 5, 2022

A minimal routing library designed to sit on top of Bun's fast HTTP server.

siopao A minimal routing library designed to sit on top of Bun's fast HTTP server. Based on Radix Tree. Sio=Hot Pao=Bun Installation bun add siopao Us

Nov 8, 2022

Monolithic repo for api server, image server, web server

Onsecondary Market Deployed at https://market.onsecondary.com Monolithic repo for api server, image server, web server TODO -use a script to cull expi

Jan 11, 2022

A tiny foundation that providing nested state-based routing for complex web application.

StateMan stateman: A tiny foundation that provides nested state-based routing for complex web applications. stateman is highly inspired by ui-router;

Dec 20, 2022
Owner
John Park
Software Engineer
John Park
TV Shows Web App - A web application based on an external API which contains information about TV shows

TV Shows Web App - A web application based on an external API which contains information about TV shows. th web app let you like the shows that you like the most and comment what you think about them making use of an involvement API to save this interaction information.

Williams Colmenares 14 Dec 17, 2022
TV Shows Web App - A web application based on an external API which contains information about TV shows

TV Shows Web App - A web application based on an external API which contains information about TV shows. th web app let you like the shows that you like the most and comment what you think about them making use of an involvement API to save this interaction information.

Williams Colmenares 14 Dec 17, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Slime jumper game is a simple game that requires you to escape from the enemies that come your way.

Slime Jumper What is this game? The slime jumper game is a game with a simple logic (but it was not so easy to do) where you have to escape from the e

Fatih 2 Mar 1, 2022
🎨ansi escape code generator to help make colorful command line tools

ansicodes ?? ansi escape code generator to help make colorful command line tools i got tired of looking up ansi code tables when writing command line

Gabe Banks 53 Dec 17, 2022
Replace ansi escape sequences with tokens indicating what they are

Replace ansi escape sequences with tokens indicating what they are

Lily Scott 3 Mar 7, 2022
Sample code for resizing Images with Lambda@Edge using the Custom Origin. You can deploy using AWS CDK.

Resizing Images with Lambda@Edge using the Custom Origin You can resize the images and convert the image format by query parameters. This Lambda@Edge

AWS Samples 16 Dec 11, 2022
A robust, minimal-server-interaction API for peer routing in the browser

Robust, minimal-server-interaction peer routing in the browser What is this? Membrane takes signalling to the browser, creating living peer networks.

Elijah Bodden 13 Jan 6, 2023