Last active
August 24, 2019 22:40
-
-
Save me2resh/8d4d5151c0666a25b0a7aa81b74cbefe to your computer and use it in GitHub Desktop.
How to pre-sign AWS API gateway requests invoking lambdas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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