安全凭证服务(STS)
STS即Secure Token Service 是一种安全凭证服务,可以使用STS来完成对于临时用户的访问授权。对于跨用户短期访问s3资源时,可以使用STS服务。这样就不需要透露主账号AK/SK,只需要生成一个短期访问凭证给需要的用户使用即可,避免主账号AK/SK泄露带来的安全风险。
class Config
{
const AccessKey = '<your-access-key>';
const SecretKey = '<your-secret-key>';
const Endpoint = '<your-endpoint>'; // e.g. http://endpoint or https://endpoint
const Bucket = '<your-bucket-name>';
const RoleSessionName = '<your-role-session-name>';
const RoleArn = '<your-role-arn>';
}
function __construct() {
$credentials = new Credentials(Config::AccessKey, Config::SecretKey);
$this->stsClient = new StsClient([
'region' => '',
'version' => '2011-06-15',
'credentials' => $credentials,
'endpoint' => Config::Endpoint,
]);
$this->bucket = Config::Bucket;
}
public function AssumeRole()
{
$bucket = '<your-bucket-Name>';
$arn = Config::RoleArn;
$roleSessionName = Config::RoleSessionName;
$roleArn = "arn:aws:iam:::role/${arn}";
$policy = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\",\"Action\":[\"s3:*\"],\"Resource\":[\"arn:aws:s3:::${bucket}\",\"arn:aws:s3:::${bucket}/*\"]}}";
try {
$res = $this->stsClient->assumeRole([
'Policy' => $policy,
'RoleArn' => $roleArn,
'RoleSessionName' => $roleSessionName,
]);
var_dump($res->get('Credentials'));
} catch (Aws\Sts\Exception\StsException $e) {
echo "Exception: $e";
}
}
参数 | 类型 | 描述 |
---|---|---|
RoleArn | String | 角色的ARN,在控制台创建角色后可以查看 |
Policy | String | 角色的policy,需要是json格式,限制长度1~2048 |
RoleSessionName | String | 角色会话名称,此字段为用户自定义,限制长度2~64 |
DurationSeconds | Integer | 会话有效期时间,默认为3600s |
public function StsClientTest(array $credentials)
{
$credentials = new Credentials($credentials['AccessKeyId'], $credentials['SecretAccessKey'], $credentials['SessionToken']);
$s3Client = new S3Client([
'region' => '',
'version' => '2006-03-01',
'credentials' => $credentials,
'endpoint' => Config::Endpoint,
]);
try {
$res = $s3Client->listObjects([
'Bucket' => $this->bucket,
]);
var_dump($res->get('Contents'));
} catch (Aws\S3\Exception\S3Exception $e) {
echo "Exception: $e";
}
}