

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用为 Amazon S3 对象创建预签名 URL CloudShell
<a name="tutorial-presigned-url"></a>

本教程向您展示如何创建预签名 URL 以便与他人共享 Amazon S3 对象。由于对象所有者在共享时会指定自己的安全凭证，因此任何收到预签名 URL 的人都可以在有限的时间内访问该对象。

## 先决条件
<a name="prerequesities-presigned"></a>
+ 具有**AWSCloudShellFullAccess**策略提供的访问权限的 IAM 用户。
+ 有关创建预签名 URL 所需的 IAM 权限，请参阅《Amazon Simple Storage Service 用户指南》**中的[与其他用户共享对象](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html)。

## 步骤 1：创建 IAM 角色以授予对 Amazon S3 存储桶的访问权限
<a name="create-role-for-sharing"></a>

此步骤介绍如何创建 IAM 角色以授予对 Amazon S3 存储桶的访问权限。

1. 要获取可以共享的 IAM 详细信息，请从 AWS CloudShell中调用 `get-caller-identity` 命令。

   ```
   aws sts get-caller-identity
   ```

   如果调用成功，命令行将显示类似如下内容的响应：

   ```
   {
       "Account": "123456789012", 
       "UserId": "AROAXXOZUUOTTWDCVIDZ2:redirect_session", 
       "Arn": "arn:aws:sts::531421766567:assumed-role/Feder08/redirect_session"
   }
   ```

1. 获取您在上一步中获得的用户信息，并将其添加到 CloudFormation 模板中。此模板创建一个 IAM 角色。该角色向您的合作者授予对共享资源的最低权限。

   ```
   Resources:
     CollaboratorRole:
       Type: AWS::IAM::Role
       Properties: 
         AssumeRolePolicyDocument: 
           Version: 2012-10-17		 	 	 
           Statement: 
             - Effect: Allow
               Principal:
                 AWS: "arn:aws:iam::531421766567:role/Feder08"
               Action: "sts:AssumeRole"
         Description: Role used by my collaborators
         MaxSessionDuration: 7200
     CollaboratorPolicy:
       Type: AWS::IAM::Policy
       Properties: 
         PolicyDocument: 
           Version: 2012-10-17		 	 	 
           Statement:
             - Effect: Allow
               Action:
                 - 's3:*'
               Resource: 'arn:aws:s3:::<YOUR_BUCKET_FOR_FILE_TRANSFER>'
               Condition:
                 StringEquals:
                   s3:prefix:
                    - "myfolder/*"
         PolicyName: S3ReadSpecificFolder
         Roles: 
           - !Ref CollaboratorRole
   Outputs:
     CollaboratorRoleArn:
       Description: Arn for the Collaborator's Role
       Value: !GetAtt CollaboratorRole.Arn
   ```

1. 将 CloudFormation 模板保存在名为的文件中`template.yaml`。

1. 使用模板部署堆栈并通过调用 `deploy` 命令创建 IAM 角色。

   ```
   aws cloudformation deploy --template-file ./template.yaml --stack-name CollaboratorRole --capabilities CAPABILITY_IAM
   ```

## 生成预签名 URL
<a name="generate-the-url"></a>

此步骤介绍如何生成预签名 URL。

1. 在中使用您的编辑器 AWS CloudShell，添加以下代码。此代码创建了一个 URL，为联合用户提供了直接访问 AWS 管理控制台的权限。

   ```
   import urllib, json, sys
   import requests
   import boto3
   import os
   
   def main():
     sts_client = boto3.client('sts')
     assume_role_response = sts_client.assume_role(
         RoleArn=os.environ.get(ROLE_ARN),
         RoleSessionName="collaborator-session"
     )
     credentials = assume_role_response['Credentials']
     url_credentials = {}
     url_credentials['sessionId'] = credentials.get('AccessKeyId')
     url_credentials['sessionKey'] = credentials.get('SecretAccessKey')
     url_credentials['sessionToken'] = credentials.get('SessionToken')
     json_string_with_temp_credentials = json.dumps(url_credentials)
     print(f"json string {json_string_with_temp_credentials}")
   
     request_parameters = f"?Action=getSigninToken&Session={urllib.parse.quote(json_string_with_temp_credentials)}"
     request_url = "https://signin.aws.amazon.com/federation" + request_parameters
     r = requests.get(request_url)
     signin_token = json.loads(r.text)
     request_parameters = "?Action=login" 
     request_parameters += "&Issuer=Example.org" 
     request_parameters += "&Destination=" + urllib.parse.quote("https://us-west-2.console.aws.amazon.com/cloudshell")
     request_parameters += "&SigninToken=" + signin_token["SigninToken"]
     request_url = "https://signin.aws.amazon.com/federation" + request_parameters
   
     # Send final URL to stdout
     print (request_url)
   
   if __name__ == "__main__":
     main()
   ```

1. 将代码保存在名为 `share.py` 的文件中。

1. 从命令行运行以下命令，以从 CloudFormation中检索 IAM 角色的 Amazon 资源名称（ARN）。然后，在 Python 脚本中使用它来获取临时安全凭证。

   ```
   ROLE_ARN=$(aws cloudformation describe-stacks --stack-name CollaboratorRole --query "Stacks[*].Outputs[?OutputKey=='CollaboratorRoleArn'].OutputValue" --output text) python3 ./share.py 
   ```

   该脚本返回一个网址，合作者可以点击该网址将他们带到该网址 AWS CloudShell 。 AWS 管理控制台在接下来的 3600 秒（1 小时）内，合作者可以完全控制在 Amazon S3 存储桶中的 `myfolder/` 文件夹。凭证在 1 小时后到期。在此时间之后，合作者将无法再访问该存储桶。