Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure a Serverless S3 bucket resource to use a CORS AllowOrigin set to the http endpoint of its function

I'm using Serverless to create a web application that serves its static content, e.g. a web font, from a S3 bucket. The S3 bucket is configured as a resource in my serverless.yml file. Its CORS configuration has an AllowOrigin set to a wildcard.

I want to change this to have an AllowOrigin with the http endpoint of the service as created by Serverless, e.g. 31alib51b6.execute-api.eu-west-1.amazonaws.com.

I wondered if it's possible to configure this in the serverless.yml file itself.

My example serverless.yml file:

service: example-service

provider:
  name: aws
  runtime: nodejs4.3
  region: eu-west-1

functions:
  web:
    handler: handler.handler
    name: ${self:service}-${self:provider.stage}
    description: ${self:service} web application - ${self:provider.stage}
    events:
      - http:
        path: web
        method: get
      - http:
        path: web/{proxy+}
        method: get

resources:
  Resources:
    S3Assets:
      Type: AWS::S3::Bucket
      Properties: 
        BucketName: ${self:service}-${self:provider.stage}-assets
        CorsConfiguration:
          CorsRules:
            - AllowedMethods:
                - GET
                - HEAD
              AllowedOrigins:
                - "*"
like image 723
ckuijjer Avatar asked Jan 25 '17 19:01

ckuijjer


People also ask

How do I configure CORS on my bucket?

In the Buckets list, choose the name of the bucket that you want to create a bucket policy for. Choose Permissions. In the Cross-origin resource sharing (CORS) section, choose Edit. In the CORS configuration editor text box, type or copy and paste a new CORS configuration, or edit an existing configuration.

How do I handle CORS with html2canvas and AWS S3 images?

You have to either load your image with the crossOrigin attribute set to 'anonymous' directly in your document, or you can try useCORS h2c option. allowTaint option does just say that you don't care if it taints the canvas or not.


1 Answers

You can define the AllowedOrigin with the following statement:

    CorsConfiguration:
      CorsRules:
        - AllowedMethods:
            - GET
            - HEAD
          AllowedOrigins:
            - Fn::Join:
              - ""
              - - "https://"
                - Ref: ApiGatewayRestApi
                - ".execute-api.eu-west-1.amazonaws.com"

"Ref: ApiGatewayRestApi" references the internal name of the generated API.

like image 137
jens walter Avatar answered Sep 22 '22 11:09

jens walter