首页 > 解决方案 > PHP / AWS:使用用户身份在 AWS S3 中私下保存图像(登录 Cognito)

问题描述

我是 AWS 技术的新手。我有PHP的知识。目前我分别创建了两个函数,

  1. 使用托管 UI (AWS) 登录
  2. 从 S3 存储桶保存和检索图像。

我已经成功地做到了这一点。但现在我想私下保存图像。意思是用户登录系统后,可以上传图片并私下保存图片。上传后只有该用户可以看到图像。下面是我单独执行的示例代码。

登录认知(托管 UI)

    <?php
    namespace AWSCognitoApp;
    require_once('vendor/autoload.php');
    use Aws\CognitoIdentityProvider\CognitoIdentityProviderClient;
    ?>


    <!DOCTYPE html>
    <html>
    <head>
        <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;400&display=swap" rel="stylesheet">
        <style>
            body{
                font-family: 'Roboto', sans-serif;
            }
        </style>
    </head>
    <body>
    <h1>DEMO WEB COGNITO CLIENT APPLICATION</h1>


    <?php
    if(!isset($_GET["access_token"]))
    {
        
    ?>
    <script>
        var url_str = window.location.href;
        //On successful authentication, AWS Cognito will redirect to Call-back URL and pass the access_token as a request parameter. 
        //If you notice the URL, a “#” symbol is used to separate the query parameters instead of the “?” symbol. 
        //So we need to replace the “#” with “?” in the URL and call the page again.
        
        if(url_str.includes("#")){
            var url_str_hash_replaced = url_str.replace("#", "?");
            window.location.href = url_str_hash_replaced;
        }
        
    </script>

    <?php
    }
    else{
    ?>

    <?php

    $access_token = $_GET["access_token"];

    $region = 'ap-southeast-1';
    $version = 'latest';

    //Authenticate with AWS Acess Key and Secret
    $client = new CognitoIdentityProviderClient([
        'version' => $version,
        'region' => $region,
        'credentials' => [
                        'key'    => '',
                        'secret' => '',
                    ],
    ]);

    try {
        //Get the User data by passing the access token received from Cognito
        $result = $client->getUser([
            'AccessToken' => $access_token,
        ]);
        
        //print_r($result);
        
        $user_email = "";
        $user_phone_number = "";
            
        //Iterate all the user attributes and get email and phone number
        $userAttributesArray = $result["UserAttributes"];
        foreach ($userAttributesArray as $key => $val) {
            if($val["Name"] == "email"){
                $user_email = $val["Value"];
            }
            if($val["Name"] == "phone_number"){
                $user_phone_number = $val["Value"];
            }
        }   
        echo '<h2>Logged-In User Attributes</h2>';
        echo '<p>User E-Mail : ' . $user_email . '</p>';
        echo '<p>User Phone Number : ' . $user_phone_number . '</p>';
        echo '<p>Token : ' . $access_token . '</p>';
        echo "<a href='secure_page.php?logout=true&access_token=$access_token'>SIGN OUT</a>";
        
        if(isset($_GET["logout"]) && $_GET["logout"] == 'true'){
            //This will invalidate the access token
            $result = $client->globalSignOut([
                'AccessToken' => $access_token,
            ]);
            
            header("Location: https://firstaiddev-ui.auth.ap-southeast-1.amazoncognito.com/login?xxxxxxxxxxx/index.php");
            
        }
        
        
    } catch (\Aws\CognitoIdentityProvider\Exception\CognitoIdentityProviderException $e) {
        echo 'FAILED TO VALIDATE THE ACCESS TOKEN. ERROR = ' . $e->getMessage();
        }
    catch (\Aws\Exception\CredentialsException $e) {
        echo 'FAILED TO AUTHENTICATE AWS KEY AND SECRET. ERROR = ' . $e->getMessage();
        }

    }
    ?>

    </body>
    </html>

上传.php

    <?php

        require 'vendor/autoload.php';
        require 'connect.php';

        date_default_timezone_set("Asia/Kuala_Lumpur");
        
        use Aws\S3\S3Client;
        use Aws\S3\Exception\S3Exception;

        // AWS Info
        $bucketName = 'kkkkk';
        $IAM_KEY = 'jjjjj';
        $IAM_SECRET = 'xxxx';
        $IAM_TOKEN = 'huhuhu';
        // Connect to AWS
        try {
            // You may need to change the region. It will say in the URL when the bucket is open
            // and on creation.
            $s3 = S3Client::factory(
                array(
                    'credentials' => array(
                        'key' => $IAM_KEY,
                        'secret' => $IAM_SECRET,
                        'token' => $IAM_TOKEN
                    ),
                    'version' => 'latest',
                    'region'  => 'ap-southeast-1'
                )
            );
        } catch (Exception $e) {
            // We use a die, so if this fails. It stops here. Typically this is a REST call so this would
            // return a json object.
            die("Error: " . $e->getMessage());
        }

        $pathInS3 = 'https://tgfirstaid-dev.s3-ap-southeast-1.amazonaws.com/' . $bucketName . '/' . $keyName;

        // Add it to S3
        try {
            // Uploaded:
            $file = $_FILES["fileToUpload"]['tmp_name'];

            $s3->putObject(
                array(
                    'Bucket'=>$bucketName,
                    'Key' =>  $keyName,
                    'SourceFile' => $file,
                    'ACL'        => 'private',
                )
            );

            

        } catch (S3Exception $e) {
            die('Error:' . $e->getMessage());
        } catch (Exception $e) {
            die('Error:' . $e->getMessage());
        }

        echo 'Done';
    ?>

标签: phpamazon-web-servicesamazon-s3amazon-cognito

解决方案


推荐阅读