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:
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?
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.