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

Notice A validity period must be set for an STS temporary access credential and a signed URL. When you use an STS temporary account credential 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 access credential to 1,200 seconds and the validity period of your signed URL generated by using this credential to 3,600 seconds. In this case, the signed URL cannot be used to upload objects after the STS temporary access credential expires, even if the signed URL is within its validity period.

Use STS for temporary access authorization

You can use Alibaba Cloud STS to authorize temporary access to OSS. STS is a web service that provides temporary access tokens for users. You can use STS to grant an access credential that has a custom validity period and custom permissions for a third-party application or a Resource Access Management (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.
Note For more information about how to configure STS, see Use a temporary access credential provided by STS to access OSS. You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain a temporary access credential. For more information, see STS SDK overview. The temporary access credential contains a security token and a temporary AccessKey pair. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. The minimum validity period of a temporary access credential is 900 seconds. The maximum validity period of a temporary access credential is the maximum session duration specified for the current role. For more information, see Specify the maximum session duration for a RAM role.
The following code provides an example on how to use STS to generate a temporary access credential.
Notice To use the express module, make sure that the module is installed. To install the express module, run npm install express --save.
// Use STS to generate a temporary access credential. The temporary access credential contains a security token and a temporary AccessKey pair. The AccessKey pair 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 access 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 O&M. 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);
  });
});
The following code provides an example on how to use the temporary access credential to initialize an OSSClient instance on the client and then use the instance to temporarily access OSS resources:
const axios = require("axios");
const OSS = require("ali-oss");

// Use the temporary access credential to initialize the OSSClient instance on the client and then use the instance to temporarily access OSS resources. 
const getToken = async () => {
  // Specify the address that the client uses to request the credential. 
  await axios.get("https:/xxx/sts").then((token) => {
    const client = new OSS({
       // Set yourRegion to the endpoint of the region in which 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 name of the bucket. Example: examplebucket. 
      bucket: "examplebucket",
      // Refresh the temporary access credential. 
      refreshSTSToken: async () => {      
        const refreshToken = await axios.get("https://127.0.0.1/sts");
        return {
          accessKeyId: refreshToken.AccessKeyId,
          accessKeySecret: refreshToken.AccessKeySecret,
          stsToken: refreshToken.SecurityToken,
        };
      },
    });
  });
};

The following table describes the STS-related parameters. 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 Roles. On the 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 null The policy that specifies the permissions of the returned STS credential.

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

The value of the parameter 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 that you can customize to identify the RAM user for which an access credential is generated. You can audit the access of users that use different security tokens based on the value of this parameter.

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

Use a signed URL for temporary access authorization

The following section provides examples on how to use a signed URL 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. By default, the validity period of a signed URL is 3,600 seconds. The maximum validity period of a signed URL is 32,400 seconds.

  • Use the signed URL 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. By default, the validity period is 1,800 seconds. For more information about other parameters, visit GitHub.

    The following code provides an example on how to generate a signed URL for object uploads and downloads:

    const OSS = require('ali-oss');
    
    const client = new OSS({
      // Set yourRegion to the endpoint of the region in which 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 access 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 O&M. 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 download the exampleobject.txt object. By default, if you use the signed URL in a browser to access the object, the object is previewed but not downloaded. 
    // Specify the full path of the object. The path cannot contain the bucket name. 
    const url = client.signatureUrl('exampleobject.txt');
    console.log(url);
    
    // Obtain the signed URL used to download the exampleobject.txt object, and set the Content-Disposition header to attachment. This way, if you use the signed URL to access the object in a browser, the object is automatically downloaded, and you can specify the name of the downloaded object. 
    // To preview the object when you use the signed URL to access the object in a browser, set the Content-Disposition header to inline and use the custom domain name that is mapped to the bucket to access the object. 
    const filename = 'ossdemo.txt' // Customize the name of the downloaded object. 
    const response = {
      'content-disposition': `attachment; filename=${encodeURIComponent(filename)}`
    }
    // Specify the full path of the object. The path cannot contain the bucket name. 
    const url = client.signatureUrl('exampleobject.txt', { response });
    console.log(url);
    
    // Obtain the signed URL used to upload the exampleobject.txt object and set the validity period of the URL. 
    // Specify the full path of the object. The path cannot contain the bucket name. 
    const url = client.signatureUrl('exampleobject.txt', {
       // Set the validity period of the signed URL. By default, the validity period is 1,800 seconds. 
      expires: 3600, 
      // Set the request method to PUT. By default, the request method is GET. 
      method: 'PUT'  
    });
    console.log(url);
    
    // Obtain the signed URL used to upload the exampleobject.txt object and set Content-Type. 
    // Specify the full path of the object. The path cannot contain the bucket name. 
    const url = client.signatureUrl('exampleobject.txt', {
      expires: 3600, 
      method: 'PUT',
      'Content-Type': 'text/plain; charset=UTF-8',
    });
    console.log(url);
  • Generate a signed URL that includes Image Processing (IMG) parameters

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

    let OSS = require('ali-oss');
    let store = new OSS({
      // Set yourRegion to the endpoint of the region in which 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 access 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 O&M. 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 an image object named exampleobject.png. 
    // Specify the full path of the object. The path cannot contain the bucket name. 
    const url = store.signatureUrl('exampleobject.png', {
      process: 'image/resize,w_200' // Set IMG parameters used to process the image. 
    });
    console.log(url);
    
    // Obtain the signed URL used to process the exampleobject.png image and set the validity period of the URL. 
    // Specify the full path of the object. The path cannot contain the bucket name. 
    const url = store.signatureUrl('exampleobject.png', { 
      // Set the validity period of the signed URL. By default, the validity period is 1,800 seconds. 
      expires: 3600, 
      // Set IMG parameters used to process the image. 
      process: 'image/resize,w_200' 
    });
    console.log(url);