자습서: Amazon S3 객체에 대해 미리 서명된 URL 생성AWS CloudShell - AWS CloudShell

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

자습서: Amazon S3 객체에 대해 미리 서명된 URL 생성AWS CloudShell

이 자습서에서는 Amazon S3 객체를 다른 사람과 공유하기 위해 미리 서명된 URL을 생성하는 방법을 보여줍니다. 객체 소유자는 공유할 때 자체 보안 자격 증명을 지정하므로 미리 서명된 URL을 받는 사람은 누구나 제한된 시간 동안 객체에 액세스할 수 있습니다.

사전 조건

  • AWSCloudShellFullAccess정책에서 제공하는 액세스 권한을 가진 IAM 사용자입니다.

  • 미리 서명된 URL을 생성하는 데 필요한 IAM 권한은 Amazon Simple Storage Service 사용 설명서의 다른 사람과 객체 공유를 참조하십시오.

1단계: Amazon S3 버킷에 액세스할 수 있는 IAM 역할 생성

  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" }
  2. 이전 단계에서 가져온 사용자 정보를 가져와서AWS 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
  3. 이름이 지정된 파일에AWS CloudFormation 템플릿을 저장합니다template.yaml.

  4. 템플릿을 사용하여 스택을 배포하고deploy 명령을 호출하여 IAM 역할을 생성합니다.

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

미리 서명된 URL 생성

  1. 에서AWS CloudShell 편집기를 사용하여 다음 코드를 추가합니다. 이 코드는 페더레이션 사용자에게 직접 액세스할 수 있는 URL을 생성합니다AWS Management Console.

    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()
  2. 라는 파일에 코드를 저장합니다share.py.

  3. 명령줄에서 다음을 실행하여 IAM 역할의 Amazon 리소스 이름 (ARN) 을AWS CloudFormation 검색합니다. 그런 다음Python 스크립트에서 이를 사용하여 임시 보안 자격 증명을 획득합니다.

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

    스크립트는 공동 작업자가 클릭하여 가져올 수 있는 URL을 반환합니다AWS Management Console.AWS CloudShell 협력자는 향후 3,600초 (1시간) 동안 Amazon S3 버킷의myfolder/ 폴더를 완전히 제어할 수 있습니다. 자격 증명은 한 시간 후에 만료됩니다. 이 시간이 지나면 협력자는 더 이상 버킷에 액세스할 수 없습니다.