Skip to content

Commit edf6af4

Browse files
author
gertvanhout
committed
- Add storage driver for private key to config
- Added private key caching - Improve middleware logic, check if config has minimal values set before trying to sign
1 parent ee64191 commit edf6af4

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

config/cloudfront-cookies.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
'private_key_path' => env('CLOUDFRONT_PRIVATE_KEY_PATH'),
1313

14+
'private_key_storage' => env('CLOUDFRONT_PRIVATE_KEY_STORAGE'),
15+
1416
'domain' => env('CLOUDFRONT_DOMAIN'),
1517

1618
'resource' => env('CLOUDFRONT_RESOURCE', 'http*://localhost/*'),

src/Http/Middleware/CloudfrontSignedCookiesMiddleware.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ public function handle(Request $request, Closure $next)
1616
{
1717
$cookies = collect(static::cookieNames());
1818

19-
$shouldNotSign = $cookies->every(function ($cookie) use ($request) {
19+
$shouldNotSign = config('cloudfront-cookies.resource') === '' ||
20+
config('cloudfront-cookies.key_pair_id') === '' ||
21+
config('cloudfront-cookies.private_key_path') === '' ||
22+
$cookies->every(function ($cookie) use ($request) {
2023
return $request->hasCookie($cookie);
2124
});
2225

src/LaravelCloudfrontCookies.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
use Aws\CloudFront\CloudFrontClient;
88
use Exception;
99
use Illuminate\Support\Carbon;
10+
use Illuminate\Support\Facades\Cache;
11+
use Illuminate\Support\Facades\Storage;
1012

1113
class LaravelCloudfrontCookies
1214
{
@@ -58,9 +60,18 @@ public function policy(?string $policy = null): static
5860

5961
public function get(): array
6062
{
63+
$private_key = Cache::remember('laravel_cloudfront_cookies_private_key',
64+
3600 * 24,
65+
fn () => Storage::disk(config('cloudfront-cookies.private_key_storage'))->get(config('cloudfront-cookies.private_key_path'))
66+
);
67+
68+
if (! $private_key) {
69+
throw new Exception('private key not found');
70+
}
71+
6172
return $this->client->getSignedCookie([
6273
'policy' => $this->policy,
63-
'private_key' => config('cloudfront-cookies.private_key_path'),
74+
'private_key' => $private_key,
6475
'key_pair_id' => config('cloudfront-cookies.key_pair_id'),
6576
]);
6677
}

0 commit comments

Comments
 (0)