STS相关接口
更新时间 2025-09-28 10:58:22
最近更新时间: 2025-09-28 10:58:22
STS即Secure Token Service 是一种安全凭证服务,可以使用STS来完成对于临时用户的访问授权。对于跨用户短期访问对象存储资源时,可以使用STS服务。这样就不需要透露主账号AK/SK,只需要生成一个短期访问凭证给需要的用户使用即可,避免主账号AK/SK泄露带来的安全风险。
初始化STS服务
require '/path/to/autoload.php';
use Aws\Sts\StsClient;
use Aws\Exception\AwsException;
use Aws\Credentials\Credentials;
const endpoint = '<your-endpoint>'; // e.g. http://endpoint or https://endpoint
const access_key = '<your-access-key>';
const secret_key = '<your-secret-key>';
$credentials = new Credentials(access_key, secret_key);
$this->stsClient = new StsClient([
'region' => 'ctyun', // region固定填ctyun
'version' => '2011-06-15', // sts接口版本号,固定填2011-06-15
'credentials' => $credentials,
'endpoint' => endpoint,
]);获取临时token
public function AssumeRole()
{
$bucket = '<your-bucket-name>';
$arn = '<your-role-arn>';
$roleSessionName = '<your-role-session-name>';
$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 | 否 |
使用临时token
public function StsClientTest($credentials, $endpoint, $bucket)
{
$stsCredentials = new Credentials($credentials['AccessKeyId'], $credentials['SecretAccessKey'], $credentials['SessionToken']);
$s3Client = new S3Client([
'region' => 'ctyun', // region固定填ctyun
'version' => '2006-03-01', // s3接口版本号,固定填2006-03-01
'credentials' => $stsCredentials,
'endpoint' => $endpoint,
]);
try {
$res = $s3Client->listObjects([
'Bucket' => $bucket,
]);
var_dump($res->get('Contents'));
} catch (Aws\S3\Exception\S3Exception $e) {
echo "Exception: $e";
}
}