

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 CloudShell 建立 Amazon S3 物件的預先簽章 URL
<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 詳細資訊，請呼叫 `get-caller-identity`命令 AWS CloudShell。

   ```
   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. 從命令列執行下列項目，從中擷取 IAM 角色的 Amazon Resource Name (ARN) CloudFormation。然後，在Python指令碼中使用它來取得臨時安全登入資料。

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

   指令碼會傳回協作者可以按一下的 URL，以將其帶入 AWS CloudShell 。 AWS 管理主控台協作者可以在接下來的 3，600 秒 (1 小時） 內完全控制 Amazon S3 儲存貯體中的`myfolder/`資料夾。登入資料會在一小時後過期。在此期間之後，協作者將無法再存取儲存貯體。