Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
awsdocs
GitHub Repository: awsdocs/amazon-s3-developer-guide
Path: blob/master/code_examples/php_examples/S3examples/s3-request-fed-user-with-temp-credentials.php
4084 views
1
<?php
2
//// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-developer-guide/blob/master/LICENSE-SAMPLECODE )
4
5
require 'vendor/autoload.php';
6
7
use Aws\Sts\StsClient;
8
use Aws\S3\S3Client;
9
use Aws\S3\Exception\S3Exception;
10
11
$bucket = '*** Your Bucket Name ***';
12
13
// In real applications, the following code is part of your trusted code. It has
14
// the security credentials that you use to obtain temporary security credentials.
15
$sts = new StsClient(
16
[
17
'version' => 'latest',
18
'region' => 'us-east-1']
19
);
20
21
// Fetch the federated credentials.
22
$sessionToken = $sts->getFederationToken([
23
'Name' => 'User1',
24
'DurationSeconds' => '3600',
25
'Policy' => json_encode([
26
'Statement' => [
27
'Sid' => 'randomstatementid' . time(),
28
'Action' => ['s3:ListBucket'],
29
'Effect' => 'Allow',
30
'Resource' => 'arn:aws:s3:::' . $bucket
31
]
32
])
33
]);
34
35
// The following will be part of your less trusted code. You provide temporary
36
// security credentials so the code can send authenticated requests to Amazon S3.
37
38
$s3 = new S3Client([
39
'region' => 'us-east-1',
40
'version' => 'latest',
41
'credentials' => [
42
'key' => $sessionToken['Credentials']['AccessKeyId'],
43
'secret' => $sessionToken['Credentials']['SecretAccessKey'],
44
'token' => $sessionToken['Credentials']['SessionToken']
45
]
46
]);
47
48
try {
49
$result = $s3->listObjects([
50
'Bucket' => $bucket
51
]);
52
} catch (S3Exception $e) {
53
echo $e->getMessage() . PHP_EOL;
54
}
55
56