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