serverless-application-model icon indicating copy to clipboard operation
serverless-application-model copied to clipboard

Enable CORS options in `Api` event type

Open lmammino opened this issue 8 years ago • 18 comments

Description:

At the moment it seems to be possible to use the Cors options only with resources of type AWS::Serverless::Api, for which you have to create a dedicated swagger file.

I have seen pretty often people preferring to just create Lambda functions by using the type AWS::Serverless::Function and then attaching to it an event of type Api.

I was expecting the Cors option to be exposed to an Api event as well, but that's apparently not the case.

Example:

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: Some sample API

Resources:
  purchaseTicket:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: index.purchaseTicket
      Runtime: nodejs8.10
      Role: !GetAtt MyRole.Arn
      Events:
        Endpoint:
          Type: Api
          Properties:  # <--- No way to define Cors here!
            Path: /purchase
            Method: post

Is there something I am missing here? If this is really a missing feature, is there any plan to include support for the Cors option in the Api event type?

Personally, I think it will be very convenient to have this and I am quite sure it would lead to a more consistent Developer Experience.

lmammino avatar Apr 07 '18 10:04 lmammino

This is available. Cors is exposed on API using Globals. You can define Cors for all your APIs but not at individual API level.

sanathkr avatar Apr 07 '18 15:04 sanathkr

Thanks for the quick reply @sanathkr, do you have an example for this?

lmammino avatar Apr 07 '18 16:04 lmammino

Skip that, Just found it :) https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#globals-section

Gonna close the issue! Thanks!

lmammino avatar Apr 07 '18 16:04 lmammino

https://github.com/awslabs/serverless-application-model/blob/develop/examples/2016-10-31/implicit_api_settings/template.yaml

sanathkr avatar Apr 07 '18 17:04 sanathkr

Doc update? I have been asked this question once or twice already as well.

jfuss avatar Apr 07 '18 17:04 jfuss

@sanathkr, @jfuss : I just updated my serverless/SAM workshop to use globals and the CORS options: https://github.com/lucpod/ticketless

Maybe there are parts of it that can be reused to improve the docs. CORS is introduced in Lesson 6.

What do you guys think?

lmammino avatar Apr 08 '18 12:04 lmammino

@lmammino Hey! I was going through your lessons. You have done a fabulous job with explaining serverless and SAM specifically. I will start a Github Issue for writing SAM User Guide and tag you. Let’s put our thoughts together to come up with a structure and potentially borrow some aspects of your docs into this user guide.

A user guide for SAM is really needed.

sanathkr avatar Apr 08 '18 16:04 sanathkr

Just in case it might help anyone, here's a link to the AWS Startup Kit Serverless Workload, which has CORS enabled for its sample RESTful API: https://github.com/aws-samples/startup-kit-serverless-workload.

rabowskyb avatar May 10 '18 19:05 rabowskyb

Hello!

I'm really struggling getting CORS working with my POST method. I've attempted the SAM globals route - with no success. The OPTIONS method is created, but the headers are not added to the POSTT response.

Likewise, the longer route of manually adding a options method and post response as described here https://docs.aws.amazon.com/apigateway/latest/developerguide/enable-cors-for-resource-using-swagger-importer-tool.html just does not seem to work.

Happy to post examples, but wondered if anyone else had this problem?

tkeeber avatar Oct 29 '18 09:10 tkeeber

agree with @tkeeber Global cors option is only doing half work, its still a pain to get it working.

manishgkasera avatar Nov 03 '18 04:11 manishgkasera

@tkeeber , I had a similar problem. According to here, there are actually two ways of authorizing CORS:

  • Via a "preflight request" to OPTIONS
  • Via headers on the direct response

Apparently Preflight requests aren't made on "simple requests" ("a GET request or a POST request with form data that has no authentication"). If you're in that bucket (as I am!), you will need to set the headers manually on your response. Here's an example where I added them manually - though if you're using Python, you may prefer this.

scubbo avatar Jan 02 '19 17:01 scubbo

Same problem. I have allowed Cors on AWS::Serverless::API, but it is still not working.

MatteoGioioso avatar Nov 06 '19 00:11 MatteoGioioso

@MatteoGioioso Can you share your template and the exact issue you are facing? We would love to root cause the issue..

praneetap avatar Nov 08 '19 18:11 praneetap

@praneetap Thanks for the answer. I took another approach. I just assign these headers on my response

"Access-Control-Allow-Origin":  "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "*",

MatteoGioioso avatar Nov 09 '19 07:11 MatteoGioioso

This is available. Cors is exposed on API using Globals. You can define Cors for all your APIs but not at individual API level.

@sanathkr Do you think it's possible to set on an individual API level now? Else what is the best practice to handle different headers for public and private APIs? (IE. I want private APIs to have authorization header and public NOT to have authorization header. I would like to avoid two different YAML files, but that seems like one way to do it.

ethaneisenhard avatar Jul 04 '20 03:07 ethaneisenhard

i still have problems enabling CORS in my app. Here is a snippet from my SAM template

Globals:
  Api:
    Cors:
      AllowMethods: "'*'"
      AllowHeaders: "'*'"
      AllowOrigin: "'*'"

Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
      Auth:
        Authorizers:
          MyCognitoAuthorizer: ...

  getByIdFunc:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handler.handle
      MemorySize: 128
      Policies: ...
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /{id}
            Method: GET
            RestApiId: !Ref MyApi

but unfortunately no headers are set in the API response. any ideas? adding the header to the response myself works fine but i rather have it defined in the template.

jaads avatar Apr 12 '21 11:04 jaads

@jaads I don't know if you found a solution for this, but code below should help you. This is the only way I found, not even adding headers to the response manually worked for me!

AWSTemplateFormatVersion: 2010-09-09 Transform: AWS::Serverless-2016-10-31 Description: S3 Uploader application Parameters: S3UploadBucket: Type: String Resources: MyApi: Type: AWS::Serverless::HttpApi Properties: CorsConfiguration: AllowMethods: - GET - POST - DELETE - OPTIONS AllowHeaders: - "" AllowOrigins: - "" TagsRequestFunction: Type: AWS::Serverless::Function Properties: CodeUri: getObjectTags/ Handler: app.handler Runtime: nodejs12.x Timeout: 3 MemorySize: 128 Environment: Variables: UploadBucket: !Ref S3UploadBucket Policies: - Statement: - Effect: Allow Resource: - !Sub "arn:aws:s3:::${S3UploadBucket}" - !Sub "arn:aws:s3:::${S3UploadBucket}/" Action: - s3: Events: UploadAssetAPI: Type: HttpApi Properties: Path: /tags Method: get ApiId: !Ref MyApi UploadRequestFunction: Type: AWS::Serverless::Function Properties: CodeUri: getSignedURL/ Handler: app.handler Runtime: nodejs12.x Timeout: 3 MemorySize: 128 Environment: Variables: UploadBucket: !Ref S3UploadBucket Policies: - S3WritePolicy: BucketName: !Ref S3UploadBucket Events: UploadAssetAPI: Type: HttpApi Properties: Path: /uploads Method: get ApiId: !Ref MyApi Outputs: APIendpoint: Description: "HTTP API endpoint URL" Value: !Sub "https://${MyApi}.execute-api.${AWS::Region}.amazonaws.com"

PS: Sorry for tabulation, couldn't copy any better

nachogonzalezqq avatar Sep 18 '21 18:09 nachogonzalezqq

@jaads

any ideas?

See this SO Post. TLDR: the AWS CORS configuration only satisfies CORS preflight requests; you still need to add the appropriate headers to your actual lambda responses.

ColmBhandal avatar Jul 08 '22 14:07 ColmBhandal