Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and assign API Key to a created stage-API using serverless?

I want to create a secure APIG using serverless, in my current "s-fuction.json" I've already have:

"apiKeyRequired": true,

And in my "s-resources-cf.json" I already have:

"AWSApiKey": {
  "Type": "AWS::ApiGateway::ApiKey",
  "Properties" : {
    "Description" : "ApiKey for secure the connections to the xxx API",
    "Enabled" : true
  }
}

It correctly creates all, a Lambda, an APIG for that lambda (including CORS) and the API Key, but I need to manually "assign" the key to the generated APIG-Stage, do you have any ideas on how could I do this automatically using serverless?

I've read the AWS documentation about the feature I want (and It seems it is possible) from here: AWS CloudFormation API Key

The documentation shows that it can be done by:

"ApiKey": {
  "Type": "AWS::ApiGateway::ApiKey",
  "DependsOn": ["TestAPIDeployment", "Test"],
  "Properties": {
    "Name": "TestApiKey",
    "Description": "CloudFormation API Key V1",
    "Enabled": "true",
    "StageKeys": [{
      "RestApiId": { "Ref": "RestApi" },
      "StageName": "Test"
    }]
  }
}

But I don't know how add a reference to the APIG automatically created by serverless and how to wait for that APIG is created.

like image 738
edgerch Avatar asked Apr 26 '16 23:04

edgerch


People also ask

Can an API be serverless?

Among numerous alternative ways of creating an API, serverless is one approach gaining popularity during the last few years because of its cost efficiency, scalability, and relative simplicity.


1 Answers

You can specify a list of API keys to be used by your service Rest API by adding an apiKeys array property to the provider object in serverless.yml. You'll also need to explicitly specify which endpoints are private and require one of the api keys to be included in the request by adding a private boolean property to the http event object you want to set as private. API Keys are created globally, so if you want to deploy your service to different stages make sure your API key contains a stage variable as defined below. When using API keys, you can optionally define usage plan quota and throttle, using usagePlan object.

Here's an example configuration for setting API keys for your service Rest API:

service: my-service
provider:
  name: aws
  apiKeys:
    - myFirstKey
    - ${opt:stage}-myFirstKey
    - ${env:MY_API_KEY} # you can hide it in a serverless variable
  usagePlan:
    quota:
      limit: 5000
      offset: 2
      period: MONTH
    throttle:
      burstLimit: 200
      rateLimit: 100
functions:
  hello:
    events:
      - http:
          path: user/create
          method: get
          private: true

For more info read the following doc: https://serverless.com/framework/docs/providers/aws/events/apigateway

like image 180
Reza Mousavi Avatar answered Sep 20 '22 12:09

Reza Mousavi