edit-icon download-icon

Use STS to access OSS

Last Updated: Dec 22, 2017

OSS can temporarily grant authorization for access through the Alibaba Cloud STS service. For more information about STS, see Concepts.

Follow the steps to use the STS:

  1. Create a subaccount in the console of the official website. For more information, see Overview.

  2. Create an STS role in the console and grant permission to the role of the subaccount. For more information, see Overview.

  3. Use the subaccount’s AccessKeyID/AccessKeySecret to apply for a temporary token from STS.

  4. Use the authentication information in the temporary token to create an OSS client.

  5. Use the OSS client to access the OSS service.

You must set the :sts_token parameter to access OSS through STS. See the following example:

  1. require 'aliyun/sts'
  2. require 'aliyun/oss'
  3. sts = Aliyun::STS::Client.new(
  4. access_key_id: '<AccessKeyId of the subaccount>',
  5. access_key_secret: '<AccessKeySecret of the subaccount>')
  6. token = sts.assume_role('<role-arn>', '<session-name>')
  7. client = Aliyun::OSS::Client.new(
  8. endpoint: '<endpoint>',
  9. access_key_id: token.access_key_id,
  10. access_key_secret: token.access_key_secret,
  11. sts_token: token.security_token)
  12. bucket = client.get_bucket('my-bucket')

You can customize an STS policy when applying for a temporary token from STS. The requested temporary permission is the intersection of the permission assigned to the role and the permission specified by the STS policy. The following code applies for the read-only permission on my-bucket using a specified STS policy and sets the temporary token validity period to 15 minutes:

  1. require 'aliyun/sts'
  2. require 'aliyun/oss'
  3. sts = Aliyun::STS::Client.new(
  4. access_key_id: '<AccessKeyId of the subaccount>',
  5. access_key_secret: '<AccessKeySecret of the subaccount>')
  6. policy = Aliyun::STS::Policy.new
  7. policy.allow(['oss:Get*'], ['acs:oss:*:*:my-bucket/*'])
  8. token = sts.assume_role('<role arc>', '<session name>', policy, 15 * 60)
  9. client = Aliyun::OSS::Client.new(
  10. endpoint: 'ENDPOINT',
  11. access_key_id: token.access_key_id,
  12. access_key_secret: token.access_key_secret,
  13. sts_token: token.security_token)
  14. bucket = client.get_bucket('my-bucket')

For detailed usage and parameters, see API Documentation.

Thank you! We've received your feedback.