Get API key IDs or actual keys

Hey,

I would like to protect some of my AWS Lambda functions exposed via HTTP with a simple API key mechanism.

Serverless has the apiKeys section which will automatically generate the keys in AWS and print them after deployment.
However, only the name of the key can be set in the configuration.

In my Lambda function I need to check, which of the generated keys has been used. The HTTP Lambda proxy gives me the ID and value of the API key. The only problem is, in my application I do not have access to the keys.

I tried passing them as an environment variable like so:

provider:
  environment:
    APIKEY_ADMIN: Ref: ApiGatewayApiKey1
    APIKEY_PUBLIC: Ref: ApiGatewayApiKey2

Which results in a circular dependency. Is there any other way to get they API key value or ID without hardcoding it? Or will I have to write a custom authorizer?

Thanks

2 Likes

Hi Henrik, did you ever solve this issue?
I am trying to do something similar.

Thanks!

Hey,

I’m afraid not. I resorted to using JSON Web Tokens instead.

1 Like

Henrik, thanks for responding to my question.

For anyone finding this in the future my solution was to create an api-key-authorizer module and look up the key based upon the key name. This relies on you being able to define the key name in the serverless.yml file:

const aws = require("aws-sdk");

let apiGateway = new aws.APIGateway({
  region: process.env.REGION
});

function findApiKey(apiKeyName) {
  let apiParams = {
    includeValues: true,
    nameQuery: apiKeyName
  };
  let authorizedKey;
  apiGateway.getApiKeys(apiParams, function (err, data) {
    if (err) console.log(err, err.stack);
    else {
      authorizedKey = data.items[0].value;
    }
  });
  return authorizedKey;
}

exports.verifyAccess = (headers, apiKeyName) => {
  let requestKey = headers["x-api-key"];
  let validKey = findApiKey(apiKeyName);
  let isAuthorized = validKey === requestKey;
  return isAuthorized;
};

There’s probably a better way to do this and it’d be great to be able to reference a specific key in process.env but I could not find a way.

Hi is there any update or better way to access the generated API Keys?