Last active
October 12, 2018 10:26
-
-
Save StuMason/53ca592ff02e03523b6127408953fcac to your computer and use it in GitHub Desktop.
AWS V4 Signature Request Trait - requires AWS-PHP-SDK. Below example used in a Laravel app. Returns a signed request.
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\Traits; | |
use Psr\Http\Message\RequestInterface; | |
use Aws\Signature\SignatureV4; | |
use Aws\Credentials\CredentialProvider; | |
use Aws\Credentials\CredentialsInterface; | |
/** | |
* APIGateway calls can require a V4 signiture created using the request headers. | |
* This trait takes the service name and original request and updates with necessary headers. | |
* | |
* e.g | |
* $req = new GuzzleHttp\Psr7\Request("POST","https://awsgatewayapi.service-name.com/post",[],"{\"data\":\"some body data\"}"); | |
* $signedrequest = $this->getSignedRequest($req, "service-name"); | |
*/ | |
trait AwsV4SignedRequestTrait | |
{ | |
/** | |
* @param RequestInterface $request unsigned request | |
* @param string $service Service name to use when signing | |
* | |
* @return RequestInterface signed request | |
*/ | |
public function getSignedRequest(RequestInterface $request, string $service): RequestInterface | |
{ | |
$signitureV4 = new SignatureV4($service, config('app.awsRegion')); | |
return $signitureV4->signRequest($request, $this->getAwsCredentials()); | |
} | |
/** | |
* @return CredentialsInterface AWS Credentials | |
*/ | |
private function getAwsCredentials(): CredentialsInterface | |
{ | |
$provider = CredentialProvider::defaultProvider(); | |
return $provider()->wait(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment