Help us understand the problem. What is going on with this article?

PythonでCognito経由でS3リソースにアクセスする

More than 1 year has passed since last update.

目的

Cognito経由で一時的な認証情報を獲得し、その情報を使ってS3に対してアクセスするPythonコードを示す。Pythonについてはどうも不完全な実装しか落ちていないので載せておく。

準備

Cognito側で非認証ロールにおいて予め当該S3リソースに必要な最低限の権限を与えておくこと。

実装

以下がコード。

cognito-s3.py
        client = boto3.client('cognito-identity', 'ap-northeast-1')

        #1回目のアクセスでCognitoの認証IDを得る
        resp =  client.get_id(IdentityPoolId='ap-northeast-1:<YOUR COGNITO IDENTITY POOL ID>')
        print "\nIdentity ID: %s"%(resp['IdentityId'])
        print "\nRequest ID: %s"%(resp['ResponseMetadata']['RequestId'])

        #2回目のアクセスでSessionを確立するための認証情報を得る
        resp = client.get_credentials_for_identity(IdentityId=resp['IdentityId'])
        secretKey = resp['Credentials']['SecretKey']
        accessKey = resp['Credentials']['AccessKeyId']
        token = resp['Credentials']['SessionToken']
        print "\nToken: %s"%(token)
        print "\nSecretKey: %s"%(secretKey)
        print "\nAccessKey ID: %s"%(accessKey)
        print resp

        #認証情報を用いて S3 Object にアクセスする
        session = Session(aws_access_key_id=accessKey,
                  aws_secret_access_key=secretKey,
                  aws_session_token=token, #トークンを忘れずに!
                  region_name='ap-northeast-1')
        s3 = session.resource('s3')
        obj = s3.Object(bucket_name='<BUCKET NAME>', key='<KEY NAME>')

        #以下は単純に読み込んで長さを返す例
        response = obj.get()
        data = response['Body'].read()
        print len(data)
kempe
発言は個人の意見であり、所属団体を代表するものではありません。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした