Skip to content

Instantly share code, notes, and snippets.

@me2resh
Last active August 24, 2019 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save me2resh/8d4d5151c0666a25b0a7aa81b74cbefe to your computer and use it in GitHub Desktop.
Save me2resh/8d4d5151c0666a25b0a7aa81b74cbefe to your computer and use it in GitHub Desktop.
How to pre-sign AWS API gateway requests invoking lambdas
<?php
use Aws\Credentials\Credentials;
use GuzzleHttp\Psr7\Request;
use Aws\Signature\SignatureV4;
use Aws\Sts\StsClient;
use GuzzleHttp\Client;
/**
* Sandbox is IAM profile with the user permissions to:
* 1- execute-api:Invoke against the API Gateway resource
* 2- lambda:InvokeFunction against the Lambda function sitting behind API Gateway
*/
$region = "eu-west-1";
$profile = "sandbox";
$version = "latest";
$service = "execute-api";
$request = new Request(
'GET',
'https://zttxjunrjk.execute-api.eu-west-1.amazonaws.com/Prod/',
[]
);
$client = new StsClient([
'profile' => $profile,
'region' => $region,
'version' => $version,
]);
// Generate session token
$result = $client->getSessionToken();
// Temp Credentials
$credentials = new Credentials(
$result['Credentials']['AccessKeyId'],
$result['Credentials']['SecretAccessKey'],
$result['Credentials']['SessionToken']
);
// Construct a request signer
$signer = new SignatureV4($service, $region);
// Sign the request
$request = $signer->signRequest($request, $credentials);
// Send the request
try {
$response = (new Client)->send($request);
} catch (Exception $exception) {
$response = $exception->getResponse()->getBody(true);
echo $response;
}
echo $response->getBody()->getContents();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment