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. //endpoint or //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";
}
}