Last active
December 5, 2023 12:17
-
-
Save ejntaylor/83230fa3a0f68ac8806c562590add146 to your computer and use it in GitHub Desktop.
Middleware to sign lambda requests
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 | |
namespace App\Http\Integrations\Middleware; | |
use Aws\Credentials\CredentialProvider; | |
use Aws\Credentials\CredentialsInterface; | |
use Aws\Signature\SignatureV4; | |
use Saloon\Contracts\RequestMiddleware; | |
use Saloon\Http\PendingRequest; | |
class SignAwsRequest implements RequestMiddleware | |
{ | |
private $credentials; | |
public function __construct(CredentialsInterface $credentials = null) | |
{ | |
$this->credentials = $credentials ?? static::loadAwsCreds(); | |
} | |
public function __invoke(PendingRequest $pendingRequest): void | |
{ | |
$signedHeaders = $this->generateSignedHeaders($pendingRequest); | |
foreach ($signedHeaders as $headerName => $headerValue) { | |
$pendingRequest->headers()->add($headerName, $headerValue); | |
} | |
} | |
protected static function loadAwsCreds(): CredentialsInterface | |
{ | |
$providerCallable = CredentialProvider::defaultProvider(); | |
return $providerCallable(); | |
} | |
protected function generateSignedHeaders(PendingRequest $request): array | |
{ | |
$lambdaSignature = new SignatureV4('lambda', 'eu-west-1'); | |
return $lambdaSignature->signRequest($request->getRequest(), $this->credentials)->getHeaders(); | |
} | |
} |
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 | |
namespace App\Http\Integrations; | |
use App\Http\Integrations\Middleware\SignAwsRequest; | |
class TestConnector extends Connector | |
{ | |
public function boot(PendingRequest $pendingRequest): void | |
{ | |
if (app()->environment('production')) { | |
$pendingRequest->middleware()->onRequest(new SignAwsRequest); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment