This topic describes how to authorize temporary access to Object Storage Service (OSS) by using Security Token Service (STS) or a signed URL.

Note The validity period must be set for an STS temporary account and a signed URL. When you use an STS temporary account to generate a signed URL that is used to perform operations such as object upload and download, the minimum validity period takes precedence. For example, you can set the validity period of your STS temporary account to 1200 seconds, and that of the signed URL to 3600 seconds. You cannot use the signed URL generated by the STS temporary account to upload objects 1200 seconds after the account is generated.

Use STS to authorize temporary access

You can use STS to authorize temporary access to OSS. STS is a web service that provides temporary access tokens for cloud computing users. You can use STS to grant an access credential with a custom validity period and custom permissions for a third-party application or a RAM user managed by you. For more information about STS, see What is STS?

STS has the following benefits:

  • You need only to generate an access token and send the access token to a third-party application, instead of exposing your AccessKey pair to the third-party application. You can customize the access permissions and validity period of this token.
  • The access token automatically expires after the validity period. Therefore, you do not need to manually revoke the permissions of an access token.

For more information about how to access OSS by using STS, see Access OSS with a temporary access credential provided by STS in OSS Developer Guide.

To authorize temporary access to OSS resources, use STS to generate a temporary access credential and use the temporary access credential to initialize the OSSClient instance on the client. The following code provides an example on how to use STS to authorize temporary access:

// Use STS to generate a temporary access credential. The temporary access credential contains a security token and a temporary AccessKey pair that consists of an AccessKey ID and an AccessKey secret. 
const app = express();
const { STS } = require('ali-oss');

app.get('/sts', (req, res) => {
 let sts = new STS({
  // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your Resource Access Management (RAM) user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret'
});
  sts.assumeRole('roleArn', 'policy', 'expiration', 'sessionName').then((result) => {
    console.log(result);
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-METHOD', 'GET');
    res.json({
      AccessKeyId: result.credentials.AccessKeyId,
      AccessKeySecret: result.credentials.AccessKeySecret,
      SecurityToken: result.credentials.SecurityToken,
      Expiration: result.credentials.Expiration
    });
  }).catch((err) => {
    console.log(err);
    res.status(400).json(err.message);
  });
});

// Use the temporary access credential to initialize the OSSClient instance on the client and authorize temporary access to OSS resources. 
const fetch = require('node-fetch');
const token = await fetch('https:/xxx/sts');
const client = new OSS({
    // Set yourRegion to the endpoint of the region where the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou. 
    region: 'yourRegion',
    accessKeyId: token.AccessKeyId,
    accessKeySecret: token.AccessKeySecret,
    stsToken: token.SecurityToken,
    // Specify the bucket name. 
    bucket: 'examplebucket',
    // Refresh the temporary access credential. 
    refreshSTSToken: async () => {
        const refreshToken = await fetch('http://127.0.0.1/sts');
        return {
            accessKeyId: refreshToken.AccessKeyId,
            accessKeySecret: refreshToken.AccessKeySecret,
            stsToken: refreshToken.SecurityToken,
        }
    }
});

The following table describes the parameters related to STS. For more information, see AssumeRole.

Parameter Type Required Example Description
roleArn String Yes acs:ram::17464958********:role/ossststest The Alibaba Cloud Resource Name (ARN) of the RAM role. Format: acs:ram::$accountID:role/$roleName. In this format, $accountID specifies the ID of the Alibaba Cloud account and $roleName specifies the name of the RAM role.

To obtain the ARN information of the RAM role, log on to the RAM console. In the left-side navigation pane, click RAM Roles. On the RAM Roles page, search for and click the created RAM role. On the RAM role details page, you can view and copy the ARN information.

policy String No {"Version": "1", "Statement": [{"Action": ["oss:GetObject"], "Effect": "Allow", "Resource": ["acs:oss:*:*:examplebucket/*"]}]} The policy that specifies the permissions of the returned STS token.

You can specify an additional policy when you specify parameters to generate a temporary STS access credential. This way, you can further limit the permissions of the temporary STS access credential. If you do not specify policies, the returned temporary STS access credential has full permissions of the specified role.

The value must be 1 to 1,024 characters in length.

expiration Number No 3600 The validity period of the temporary access credential. Unit: seconds. Default value: 3600.

Minimum value: 900. Maximum value: the value of the MaxSessionDuration parameter.

Note You can call the CreateRole or UpdateRole operation to set the MaxSessionDuration parameter. For more information, see CreateRole or UpdateRole.
sessionName String Yes Alice The role session name you can customize to identify the RAM user who assumes the RAM role.

The name must be 2 to 32 characters in length and can contain letters, digits, periods (.), at signs (@), hyphens (-), and underscores (_).

Use a signed URL to authorize temporary access

The following section provides examples on how to use signed URLs to authorize temporary access:

  • Generate a signed URL

    You can generate a signed URL and provide the URL to a visitor for temporary access. When you generate a signed URL, you can specify the validity period of the URL to limit the period of access from visitors.

  • Use signed URLs to upload and download an object
    Note name {String} specifies the name of the object stored in OSS. [expires] {Number} specifies the validity period of the URL. Unit: seconds. Default value: 1800. For more information about other parameters, visit GitHub.

    The following code provides examples on how to generate signed URLs to upload and download objects:

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // Set yourRegion to the endpoint of the region where the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou. 
      region: 'yourRegion',
      // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console. 
      accessKeyId: 'yourAccessKeyId',
      accessKeySecret: 'yourAccessKeySecret',
      // Specify the bucket name. 
      bucket: 'examplebucket'
    });
    
    // Obtain the signed URL to download the exampleobject.txt object. By default, you can preview the object to download when you use a browser to access the signed URL. 
    // Specify the full path of the object. The full path of the object does not contain bucket names. 
    const url = client.signatureUrl('exampleobject.txt');
    console.log(url);
    
    // Obtain the signed URL to download the exampleobject.txt object. Configure the response header to automatically download the object when the browser accesses the signed URL and customize the name of the local file after the object is downloaded. 
    const filename = 'ossdemo.txt' // Customize the name of the local file after the object is downloaded. 
    const response = {
      'content-disposition': `attachment; filename=${encodeURIComponent(filename)}`
    }
    // Specify the full path of the object. The full path of the object does not contain bucket names. 
    const url = client.signatureUrl('exampleobject.txt', { response });
    console.log(url);
    
    // Obtain the signed URL to upload the exampleobject.txt object and set the validity period. 
    // Specify the full path of the object. The full path of the object does not contain bucket names. 
    const url = client.signatureUrl('exampleobject.txt', {
      expires: 3600, // Set the validity period. Unit: seconds. Default value: 1800. 
      method: 'PUT'  // Set the request method to PUT. By default, the request method is GET. 
    });
    console.log(url);
    
    // Obtain the signed URL to upload the exampleobject.txt object and set Content-Type. 
    // Specify the full path of the object. The full path of the object does not contain bucket names. 
    const url = client.signatureUrl('exampleobject.txt', {
      expires: 3600, 
      method: 'PUT',
      'Content-Type': 'text/plain; charset=UTF-8',
    });
    console.log(url);
  • Generate a signed object URL that includes IMG parameters

    The following code provides an example on how to generate a signed URL that includes Image Processing (IMG) parameters:

    let OSS = require('ali-oss');
    let store = new OSS({
      // Set yourRegion to the endpoint of the region where the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou. 
      region: 'yourRegion',
      // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console. 
      accessKeyId: 'yourAccessKeyId',
      accessKeySecret: 'yourAccessKeySecret',
      // Specify the bucket name. 
      bucket: 'examplebucket'
    })
    
    // Obtain the signed URL used to process the exampleobject.png image. 
    // Specify the full path of the object. The full path of the object does not contain bucket names. 
    const url = store.signatureUrl('exampleobject.png', {
      process: 'image/resize,w_200' // Set the IMG parameter used to process the image. 
    });
    console.log(url);
    
    // Obtain the signed URL used to process the exampleobject.png image and set the validity period. 
    // Specify the full path of the object. The full path of the object does not contain bucket names. 
    const url = store.signatureUrl('exampleobject.png', { 
      expires: 3600, // Set the validity period. Unit: seconds. Default value: 1800. 
      process: 'image/resize,w_200' // Set the IMG parameter used to process the image. 
    });
    console.log(url);