Skip to content

Instantly share code, notes, and snippets.

@martinjt
Last active August 29, 2022 01:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinjt/98739421411ace776e84d53d331b2ddf to your computer and use it in GitHub Desktop.
Save martinjt/98739421411ace776e84d53d331b2ddf to your computer and use it in GitHub Desktop.
Accessing API Gateway endpoints secured using IAM permissions and Assumed Roles
import fetch from 'node-fetch';
import aws4 from 'aws4';
import AWS from 'aws-sdk';
const role_arn = "";
const local_creds = new AWS.SharedIniFileCredentials({profile: 'default'});
const sts = new AWS.STS({
credentials: local_creds
});
const role_response = await sts.assumeRole({
ExternalId: "node-tester",
RoleArn: role_arn,
RoleSessionName: "execute-api-test"
}).promise();
const credentials = {
secretAccessKey: role_response.Credentials.SecretAccessKey,
accessKeyId: role_response.Credentials.AccessKeyId,
sessionToken: role_response.Credentials.SessionToken
};
const opts = {
method: "GET",
host: "",
path: "",
service: 'execute-api',
payload: "",
region: 'eu-west-2'
};
aws4.sign(opts, credentials);
const response = await fetch("https://" + opts.host + opts.path, {
headers: opts.headers
});
console.log(await response.json());
{
"name": "api-gw-auth",
"version": "1.0.0",
"description": "",
"dependencies": {
"aws-sdk": "^2.1059.0",
"aws4": "^1.11.0",
"node-fetch": "^2.6.6"
},
"devDependencies": {
},
"keywords": []
}
@toddhgardner
Copy link

Nothing explicitly wrong with any of this.

Line 34 might be easier with a template string

const response = await fetch(https://${opts.host}${opts.path}, {`

Sometimes I would see this whole thing wrapped up as a function and then called. But more of a style choice.

@martinjt
Copy link
Author

Cheers dude, appreciate the feedback!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment