Amazon Simple Storage Service
开发人员指南 (API 版本 2006-03-01)
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 Amazon AWS 入门

使用联合身份用户临时凭证创建请求 - 适用于 Ruby 的 AWS 开发工具包

您可以为联合身份用户和应用程序提供临时安全凭证,以便它们可以发送经身份验证的请求,从而访问 AWS 资源。从 IAM 服务请求临时凭证时,您必须提供用户名称和 IAM 策略 (描述您需要授予的资源权限)。默认情况下,会话的持续时间为一个小时。但是,如果使用 IAM 用户凭证来请求临时凭证,在请求适用于联合身份用户和应用程序的临时安全凭证时,您可以显式地设置其他持续时间值。有关适用于联合身份用户和应用程序的临时安全凭证的信息,请参阅创建请求

注意

为了提高请求适用于联合身份用户和应用程序的临时安全凭证时的安全性,您可能需要使用仅具有所需访问权限的专用 IAM 用户。您创建的临时用户可获取的权限不能超过请求临时安全凭证的 IAM 用户。有关更多信息,请参阅 AWS Identity and Access Management 常见问题

以下 Ruby 代码示例允许具有一组有限权限的联合身份用户列出指定存储桶中的键。

require 'aws-sdk-s3' require 'aws-sdk-iam' USAGE = <<DOC Usage: federated_create_bucket_policy.rb -b BUCKET -u USER [-r REGION] [-d] [-h] Creates a federated policy for USER to list items in BUCKET for one hour. BUCKET is required and must already exist. USER is required and if not found, is created. If REGION is not supplied, defaults to us-west-2. -d gives you extra (debugging) information. -h displays this message and quits. DOC $debug = false def print_debug(s) if $debug puts s end end def get_user(region, user_name, create) user = nil iam = Aws::IAM::Client.new(region: 'us-west-2') begin user = iam.create_user(user_name: user_name) iam.wait_until(:user_exists, user_name: user_name) print_debug("Created new user #{user_name}") rescue Aws::IAM::Errors::EntityAlreadyExists print_debug("Found user #{user_name} in region #{region}") end end # main region = 'us-west-2' user_name = '' bucket_name = '' i = 0 while i < ARGV.length case ARGV[i] when '-b' i += 1 bucket_name = ARGV[i] when '-u' i += 1 user_name = ARGV[i] when '-r' i += 1 region = ARGV[i] when '-d' puts 'Debugging enabled' $debug = true when '-h' puts USAGE exit 0 else puts 'Unrecognized option: ' + ARGV[i] puts USAGE exit 1 end i += 1 end if bucket_name == '' puts 'You must supply a bucket name' puts USAGE exit 1 end if user_name == '' puts 'You must supply a user name' puts USAGE exit 1 end #Identify the IAM user we allow to list Amazon S3 bucket items for an hour. user = get_user(region, user_name, true) # Create a new STS client and get temporary credentials. sts = Aws::STS::Client.new(region: region) creds = sts.get_federation_token({ duration_seconds: 3600, name: user_name, policy: "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:ListBucket\",\"Resource\":\"arn:aws:s3:::#{bucket_name}\"}]}", }) # Create an Amazon S3 resource with temporary credentials. s3 = Aws::S3::Resource.new(region: region, credentials: creds) puts "Contents of '%s':" % bucket_name puts ' Name => GUID' s3.bucket(bucket_name).objects.limit(50).each do |obj| puts " #{obj.key} => #{obj.etag}" end