Last active
March 18, 2021 21:33
-
-
Save bangpound/3835e43cfae524fdda00102164788698 to your computer and use it in GitHub Desktop.
AWS IAM authentication to Vault with AWS SDK v3 on PHP
This file contains 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 the AWS security token service's GetCallerIdentity command | |
// to produce a request that allows Vault to identify the instance | |
// that wants to authenticate. | |
// | |
// @see https://gist.github.com/joelthompson/378cbe449d541debf771f5a6a171c5ed | |
$sts = new \Aws\Sts\StsClient([ | |
'region' => 'us-east-1', | |
'version' => 'latest', | |
]); | |
$command = $sts->getCommand('GetCallerIdentity'); | |
// The AWS serialize function will convert a command into a PSR-7 request. | |
// @todo Append build middleware to support X-Vault-AWS-IAM-Server-ID header? | |
// @see https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_handlers-and-middleware.html#middleware | |
$request = \Aws\serialize($command); | |
$client = new \GuzzleHttp\Client(['base_uri' => $_ENV['VAULT_ADDR']]); | |
// The method, URL, body and headers of this request are encoded and sent | |
// to Vault which will send the request to AWS STS. | |
$response = $client->post('/v1/auth/aws/login', [ | |
'json' => [ | |
'role' => 'dev', | |
'iam_http_request_method' => $request->getMethod(), | |
'iam_request_url' => base64_encode($request->getUri()), | |
'iam_request_body' => base64_encode($request->getBody()), | |
'iam_request_headers' => base64_encode(\GuzzleHttp\json_encode($request->getHeaders())), | |
] | |
]); | |
$data = \GuzzleHttp\json_decode($response->getBody()); | |
$token = $data->auth->client_token; |
Thank you for this gist! To add on, the X-Vault-AWS-IAM-Server-ID can be set using:
use Aws\Middleware;
use Psr\Http\Message\RequestInterface;
$command->getHandlerList()->appendBuild(
Middleware::mapRequest(function (RequestInterface $request) {
return $request->withHeader('X-Vault-AWS-IAM-Server-ID', $serverID);
}),
'add-header'
);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for the gist.
For me the
'role' => 'dev',
was optional. So it is not required to have this parameter.