Use STS to access OSS

Last Updated: Oct 31, 2017

OSS can temporarily grant authorization for access through the Alibaba Cloud STS service.

To use STS, follow these steps:

  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 stsToken parameter to access OSS with STS, as shown in the following example:

  1. var OSS = require('ali-oss');
  2. var STS = OSS.STS;
  3. var co = require('co');
  4. var sts = new STS({
  5. accessKeyId: '<AccessKeyId of the subaccount>',
  6. accessKeySecret: '<AccessKeySecret of the subaccount>'
  7. });
  8. co(function* () {
  9. var token = yield sts.assumeRole(
  10. '<role-arn>', '<policy>', '<expiration>', '<session-name>');
  11. var client = new OSS({
  12. region: '<region>',
  13. accessKeyId: token.credentials.AccessKeyId,
  14. accessKeySecret: token.credentials.AccessKeySecret,
  15. stsToken: token.credentials.SecurityToken,
  16. bucket: '<bucket-name>'
  17. });
  18. }).catch(function (err) {
  19. console.log(err);
  20. });

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. var OSS = require('ali-oss');
  2. var STS = OSS.STS;
  3. var co = require('co');
  4. var sts = new STS({
  5. accessKeyId: '<AccessKeyId of the subaccount>',
  6. accessKeySecret: '<AccessKeySecret of the subaccount>'
  7. });
  8. var policy = {
  9. "Statement": [
  10. {
  11. "Action": [
  12. "oss:Get*"
  13. ],
  14. "Effect": "Allow",
  15. "Resource": ["acs:oss:*:*:my-bucket/*"]
  16. }
  17. ],
  18. "Version": "1"
  19. };
  20. co(function* () {
  21. var token = yield sts.assumeRole(
  22. '<role-arn>', policy, 15 * 60, '<session-name>');
  23. var client = new OSS({
  24. region: '<region>',
  25. accessKeyId: token.credentials.AccessKeyId,
  26. accessKeySecret: token.credentials.AccessKeySecret,
  27. stsToken: token.credentials.SecurityToken,
  28. bucket: '<bucket-name>'
  29. });
  30. }).catch(function (err) {
  31. console.log(err);
  32. });
Thank you! We've received your feedback.