CookieSigner.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Aws\CloudFront;
  3. class CookieSigner
  4. {
  5. /** @var Signer */
  6. private $signer;
  7. private static $schemes = [
  8. 'http' => true,
  9. 'https' => true,
  10. ];
  11. /**
  12. * @param $keyPairId string ID of the key pair
  13. * @param $privateKey string Path to the private key used for signing
  14. *
  15. * @throws \RuntimeException if the openssl extension is missing
  16. * @throws \InvalidArgumentException if the private key cannot be found.
  17. */
  18. public function __construct($keyPairId, $privateKey)
  19. {
  20. $this->signer = new Signer($keyPairId, $privateKey);
  21. }
  22. /**
  23. * Create a signed Amazon CloudFront Cookie.
  24. *
  25. * @param string $url URL to sign (can include query string
  26. * and wildcards). Not required
  27. * when passing a custom $policy.
  28. * @param string|integer|null $expires UTC Unix timestamp used when signing
  29. * with a canned policy. Not required
  30. * when passing a custom $policy.
  31. * @param string $policy JSON policy. Use this option when
  32. * creating a signed cookie for a custom
  33. * policy.
  34. *
  35. * @return array The authenticated cookie parameters
  36. * @throws \InvalidArgumentException if the URL provided is invalid
  37. * @link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-cookies.html
  38. */
  39. public function getSignedCookie($url = null, $expires = null, $policy = null)
  40. {
  41. if ($url) {
  42. $this->validateUrl($url);
  43. }
  44. $cookieParameters = [];
  45. $signature = $this->signer->getSignature($url, $expires, $policy);
  46. foreach ($signature as $key => $value) {
  47. $cookieParameters["CloudFront-$key"] = $value;
  48. }
  49. return $cookieParameters;
  50. }
  51. private function validateUrl($url)
  52. {
  53. $scheme = str_replace('*', '', explode('://', $url)[0]);
  54. if (empty(self::$schemes[strtolower($scheme)])) {
  55. throw new \InvalidArgumentException('Invalid or missing URI scheme');
  56. }
  57. }
  58. }