在AWS中自定义Credential Provider实现Client连接

今天在使用AWS中,由于原来的 key和secrect是放在配置文件ini里面的。现在需要改成从DB里面获取,所以需要自定义Credential.在AWS中重写这个挺简单的。

我这里是继承原先的CredentialProvider类,然后写了一个bucketProvider方法

使用方法:


//调用自定义provider
$provider = \app\library\Aws\S3CredentialProvider::bucketProvider();
$provider = Aws\Credentials\CredentialProvider::memoize($provider);
try {
    $s3Client = new Aws\S3\S3Client([
    'region'      => $region,
    'version'     => '2006-03-01',
    'credentials' => $provider,
    ]);
}catch (Aws\Exception\CredentialsException $ex){
	return null;
}
<?php
namespace app\library\Aws;

use Yaf\Registry;

use Aws\Credentials\CredentialProvider;
use GuzzleHttp\Promise;
use Aws\Exception\CredentialsException;
use GuzzleHttp\Promise\RejectedPromise;
use Aws\Credentials\Credentials;

/**
 * Class DB
 * @package app\library\Aws
 * awazon 自定义credential,根椐存储桶,去获取access_id 和 access_secrect;
 */
class S3CredentialProvider extends CredentialProvider
{


    public static function bucketProvider()
    {
        return function () {
            $bucketInfo = [];
            try {
                $bucketInfo = \app\library\Aws\Bucket::instance()->getBucketRegion(); //获取bucket信息。
            }catch(\Exception $ex){                
                return new Promise\RejectedPromise(new CredentialsException("获取s3认证文件失败"));
            }

            $accessKey = isset($bucketInfo['accessKey']) && $bucketInfo['accessKey'] ? json_decode($bucketInfo['accessKey'],true) : [];
            $key = isset($accessKey['id']) && $accessKey['id'] ? $accessKey['id'] : '';
            $secret = isset($accessKey['key']) && $accessKey['key'] ? $accessKey['key'] : '';
            if ($key && $secret) {
                return Promise\promise_for(
                    new Credentials($key, $secret,NULL)
                );
            }            
            return new Promise\RejectedPromise(new CredentialsException("找不到s3的key,secrect用于认证"));
        };
    }

}
posted @ 2019-01-08 11:31  随彦心MO  阅读(1263)  评论(0编辑  收藏  举报