Search code examples
amazon-web-servicesaws-api-gatewayaws-cdk

How can I configure an API gateway endpoint to require an API key?


I am building a webservice using AWS CDK. I would like to have all endpoints require an api key to allow a connection.

Currently I set up my webservice like so:

    // Define the API Gateway
    const api = new apigw.RestApi(scope, 'MyApiGateway', {
        defaultCorsPreflightOptions: {
            allowOrigins: apigw.Cors.ALL_ORIGINS,
            allowMethods: apigw.Cors.ALL_METHODS, // this is also the default
        }
    });

    const apiKeyName = 'myKeyName';
    const apiKey = new apigw.ApiKey(scope, 'api-key', {
        apiKeyName,
        enabled: true
    });

    // define the usage plan
    const usagePlan = api.addUsagePlan('UsagePlan', {
        name: 'UsagePlan',
        throttle: {
            rateLimit: 100,
            burstLimit: 200,
        },
    });

    // add the API key to the usage plan
    usagePlan.addApiKey(apiKey);

    ...

    resource.addMethod(method, integration, {
        apiKeyRequired: true,
        requestParameters: {
          'method.request.header.x-api-key': true,
        },
    });

From the console, I can see the following:

  1. The API key exists
  2. The usage plan exists, and contains the API key
  3. The endpoint says "Authorization: None, API Key: Required"

However the usage plan says there are "no associated stages", and when I actually try to call this API, passing the key either as a query parameter, or via the header, the request fails with error code 403/Forbidden.

How can I make this work?


Solution

  • You almost have it. You're missing the part where you attach a usage plan to a stage. Here's the documentation for it https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-apigateway.UsagePlan.html#addwbrapiwbrstageapistage.

    Example below:

    usagePlan.addApiStage({ stage: api.deploymentStage })