LoginSignup
36

More than 5 years have passed since last update.

Cognitoで認証して、STSで認可して、S3に画像をアップロードする。Rubyで。

Last updated at Posted at 2015-01-21

Cognitoとは

この記事が一番わかりやすかった。
http://qiita.com/imaifactory/items/b66cdf91118e3be6fe17

前提

  • test.png がおいてある
  • ARN(arn:aws:iam::00000000000:role/Cognito_photo1Auth_DefaultRole)にS3の操作権限を設定してある
ARN
{
    "Version": "2012-10-17",
    "Statement": [{
        "Action": [
            "mobileanalytics:PutEvents",
            "cognito-sync:*",
            "s3:*"
        ],
        "Effect": "Allow",
        "Resource": [
            "*"
        ]
    }]
}

実装

cognito.rb
require 'aws-sdk'

# Cognitoクライアントを作成する
cognito_identity = Aws::CognitoIdentity::Client.new(
    region: 'us-east-1',
    access_key_id: 'ACCESS KEY',
    secret_access_key: 'SECRET ACCESS KEY'
  )

# developer identityでログイン処理を行う
resp = cognito_identity.get_open_id_token_for_developer_identity(
    identity_pool_id: 'us-east-1:00000000-0000-0000-0000-000000000000',
    logins: { 'com.yujiroarai.provider' => 'abcde' }
  )

puts "Identity ID: #{resp.identity_id}"
puts "Access Token: #{resp.token}"

# STSクライアントを作成する
sts = Aws::STS::Client.new(
    region: 'ap-northeast-1',
    access_key_id: 'ACCESS KEY',
    secret_access_key: 'SECRET ACCESS KEY'
  )

# STSを使って、取得するアクセス権を定義
# user1以下の操作を許す
policy = JSON.generate(
      'Version' => '2012-10-17',
      'Statement' => [{
        'Effect' => 'Allow',
        'Action' =>  '*',
        'Resource' => 'arn:aws:s3:::s3upload-sample/user1/*'
      }]
    )

# Cognitoで取得したアクセストークンを使って、STSでアクセス権を取得する
r = sts.assume_role_with_web_identity(
    role_arn: 'arn:aws:iam::00000000000:role/Cognito_photo1Auth_DefaultRole',
    web_identity_token: resp.token,
    role_session_name: 'session_name',
    policy: policy
  )

# STSで取得したクレデンシャル情報を使って、S3クライアントを作成する
s3 = Aws::S3::Client.new(
  region: 'ap-northeast-1',
  credentials: r.credentials,
  http_wire_trace: true
)

# ファイルを読み込み
file_open = File.open('test.png')

# ファイルをアップロードする
s3.put_object(
    bucket: 's3upload-sample',
    body: file_open,
    key: 'user1/test.png'
)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36