How to cache AWS credentials in Laravel

Last time I wrote a post about how to cache AWS credentials. This time I decided to show how it can be used in Laravel.

You can create an additional adapter in your Laravel application. This time I wanted to cache AWS credentials for the S3 storage service.

Let’s create new class

app/Providers/AwsS3CredentialsServiceProvider.php

Class content:

<?php

namespace App\Providers;

use Aws\Credentials\CredentialProvider;
use Aws\DoctrineCacheAdapter;
use Aws\S3\S3Client;
use Doctrine\Common\Cache\FilesystemCache;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\Filesystem;

class AwsS3CredentialsServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        Storage::extend('s3cached', function ($app, $config) {

            $s3Config = $config;
            $s3Config['version'] = 'latest';

            if (! empty($config['key']) && ! empty($config['secret'])) {
                $s3Config['credentials'] = Arr::only($config, ['key', 'secret', 'token']);
            } else {
                $cache = new DoctrineCacheAdapter(new FilesystemCache('/tmp/cache'));
                $provider = CredentialProvider::defaultProvider();
                $s3Config['credentials'] = CredentialProvider::cache($provider, $cache);
            }

            $root = $s3Config['root'] ?? null;
            $options = $config['options'] ?? [];
            $streamReads = $config['stream_reads'] ?? false;

            return new Filesystem(new AwsS3Adapter(new S3Client($s3Config), $s3Config['bucket'], $root, $options, $streamReads), $config);
        });
    }
}

The last step we need to do is to autoload the newly created class. This can be done in the config/app.php config file in the provider’s section.

'providers' => [   App\Providers\AwsS3CredentialsServiceProvider::class,
...
]

Now let’s change or create a new config in filesystem.php. I used the same s3 config and changed the driver parameter from s3 to s3cached:

's3' => [
            'driver' => 's3cached',
            'key' => env('AWS_ACCESS_KEY_ID'),
           ...
        ],

Leave a Reply

Your email address will not be published. Required fields are marked *

5 × 4 =