php - PHP / AWS:使用用户身份在 AWS S3 中私下保存图像(登录 Cognito)
问题描述
我是 AWS 技术的新手。我有PHP的知识。目前我分别创建了两个函数,
- 使用托管 UI (AWS) 登录
- 从 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';
?>
解决方案
推荐阅读
- ios - 具有动态高度的单元格的手风琴式动画的 UITableView
- reactjs - 映射路由器的属性数组时要指定什么类型?
- c++ - 如何发送通过绑定到函数/方法创建的功能对象?
- c++ - int main() 中的内存限制
- sql - 如何按一个字段过滤唯一值?
- java - Android WorkManager:无法从 PeriodicWorkRequest 获取输出数据
- r - 如何根据其他列的字符值创建第三列,不包括 NA 和值?
- algorithm - 将十六进制数转换为十进制形式的最快算法,无需使用固定长度变量来存储结果
- django - 如何在vscode中的django-rest-framework包上放断点进行调试?
- reactjs - 如何在 NSwag Studio 生成的服务中注入 JWT 以响应打字稿