Skip to content

Instantly share code, notes, and snippets.

@bangpound
Last active March 18, 2021 21:33
Show Gist options
  • Save bangpound/3835e43cfae524fdda00102164788698 to your computer and use it in GitHub Desktop.
Save bangpound/3835e43cfae524fdda00102164788698 to your computer and use it in GitHub Desktop.
AWS IAM authentication to Vault with AWS SDK v3 on PHP
<?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;
@chaynes-ws
Copy link

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