All Products
Search
Document Center

Object Storage Service:Authorized access

Last Updated:Oct 18, 2023

This topic describes how to use temporary access credentials provided by Security Token Service (STS) or a signed URL to temporarily access Object Storage Service (OSS) resources.

Important

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

Use STS for temporary access authorization

You can use 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 temporary access credentials that have a custom validity period and custom permissions to a third-party application or a RAM user that is 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. You do not need to expose your AccessKey pair to the third-party application. You can specify the access permissions and the validity period of the access token.

  • The access token automatically expires after the validity period. Therefore, you do not need to revoke the access permissions of an access token.

To access OSS by using temporary access credentials provided by STS, perform the following steps:

Step 1: Create a RAM user

  1. Log on to the RAM console.

  2. In the left-side navigation pane, choose Identities > Users.

  3. On the Users page, click Create User.

  4. Configure the Logon Name and Display Name parameters.

  5. In the Access Mode section, select OpenAPI Access. Then, click OK.

  6. On the page that appears, click Copy to save the AccessKey pair of the RAM user.

Step 2: Grant the RAM user the AssumeRole permission

  1. On the Users page, find the RAM user that you created and click Add Permissions in the Actions column.

  2. In the Add Permissions panel, click the System Policy tab and select the AliyunSTSAssumeRoleAccess policy.image.png

  3. Click OK.

Step 3: Create a role used to obtain temporary access credentials from STS

  1. In the left-side navigation pane, choose Identities > Roles.

  2. Click Create Role. In the Create Role panel, set Select Trusted Entity to Alibaba Cloud Account and click Next.

  3. In the Create Role panel, set RAM Role Name to RamOssTest and Select Trusted Alibaba Cloud Account to Current Alibaba Cloud Account.

  4. Click OK. After the role is created, click Close.

  5. On the Roles page, enter RamOssTest in the search box and click RamOssTest in the search result.

  6. Click Copy on the right side of the RamOssTest page to save the Alibaba Cloud Resource Name (ARN) of the role.arn

Step 4: Grant the role the permissions to upload objects to and download objects from OSS

  1. Grant the role the permissions to upload objects to and download objects from a bucket by using custom policies.

    1. In the left-side navigation pane, choose Permissions > Policies.

    2. On the Policies page, click Create Policy.

    3. On the Create Policy page, click JSON. Modify the script in the policy editor to grant the role the permissions to upload objects to and download objects from a bucket named examplebucket by calling PutObject and GetObject. The following sample code provides an example on how to grant the role the permissions.

      Warning

      The following example is for reference only. You must configure fine-grained RAM policies based on your requirements to avoid granting excessive permissions to users. For more information about how to configure fine-grained RAM policies, see Example 9: Use RAM or STS to authorize other users to access OSS resources.

      {
          "Version": "1",
          "Statement": [
           {
                 "Effect": "Allow",
                 "Action": [
                   "oss:PutObject",
                   "oss:GetObject"
                 ],
                 "Resource": [
                   "acs:oss:*:*:examplebucket",
                   "acs:oss:*:*:examplebucket/*"
                 ]
           }
          ]
      }
    4. Click Next to edit policy information.

    5. In the Basic Information section, set Name to RamTestPolicy and click OK.

  2. Attach the custom policy to the RamOssTest role.

    1. In the left-side navigation pane, choose Identities > Roles.

    2. On the Roles page, find the RamOssTest role.

    3. Click Add Permissions in the Actions column.

    4. In the Add Permissions panel, click the Custom Policy tab and select the RamTestPolicy policy.

    5. Click OK.

Step 5: Generate temporary access credentials by using STS

The temporary access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. The minimum validity period of temporary access credentials is 900 seconds. The maximum validity period of temporary access credentials is the maximum session duration specified for the current role. For more information, see Specify the maximum session duration for a RAM role.

Important

To use the express module, make sure that the module is installed. To install the express module, run the npm install express --save command.

const { STS } = require('ali-oss');
const express = require("express");
const app = express();

app.get('/sts', (req, res) => {
 let sts = new STS({
  // Specify the AccessKey pair that is created for the RAM user in Step 1. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret'
});
  // Specify the Alibaba Cloud Resource Name (ARN) of the role that is created in Step 3. Example: acs:ram::175708322470****:role/ramtest. 
  // Specify the custom policies. This way, you can limit the permissions of the temporary access credentials. If you do not specify custom policies, the returned temporary access credentials have full permissions of the specified RAM role. 
  // The permissions obtained by the temporary access credentials are the intersection of the role permissions configured in Step 4 and the permissions specified by the RAM policy. 
  // expiration specifies the validity period of the temporary access credentials. Unit: seconds. The minimum validity period of the temporary access credentials is 900 seconds. The maximum validity period of the temporary access credentials is the maximum session duration specified for the current role. In this example, the validity period is set to 3,000 seconds. 
  // sessionName specifies a custom role session name, which is used to distinguish different tokens. Example: sessiontest. 
  sts.assumeRole('acs:ram::175708322470****:role/ramtest', ``, '3000', 'sessiontest').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);
  });
});
app.listen(8000,()=>{
   console.log("server listen on:8000")
})

Step 6: Use the temporary access credentials to upload objects to and download objects from OSS

  • Use the temporary access credentials to upload objects to OSS

    const axios = require("axios");
    const OSS = require("ali-oss");
    
    // Use the temporary access credentials to initialize an OSSClient instance on the client. The instance is used to authorize temporary access to OSS resources. 
    const getToken = async () => {
      // Specify the address that is used by the client to obtain the temporary access credentials. 
      await axios.get("http://localhost:8000/sts").then((token) => {
        const client = new OSS({
           // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
          region: 'oss-cn-hangzhou',
          accessKeyId: token.data.AccessKeyId,
          accessKeySecret: token.data.AccessKeySecret,
          stsToken: token.data.SecurityToken,
          // Specify the name of the bucket. 
          bucket: "examplebucket",
          // Refresh the temporary access credentials. 
          refreshSTSToken: async () => {
            const refreshToken = await axios.get("http://localhost:8000/sts");
            return {
              accessKeyId: refreshToken.AccessKeyId,
              accessKeySecret: refreshToken.AccessKeySecret,
              stsToken: refreshToken.SecurityToken,
            };
          },
        });
        // Use the temporary access credentials to upload objects to OSS. 
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.jpg. 
        // Specify the full path of the local file. Example: D:\\example.jpg. 
        client.put('exampleobject.jpg', 'D:\\example.jpg').then((res)=>{console.log(res)}).catch(e=>console.log(e))
      });
    };
    getToken()
  • Use the temporary access credentials to download objects from OSS

    const axios = require("axios");
    const OSS = require("ali-oss");
    
    // Use the temporary access credentials to initialize an OSSClient instance on the client. The instance is used to authorize temporary access to OSS resources. 
    const getToken = async () => {
      // Specify the address that is used by the client to obtain the temporary access credentials. 
      await axios.get("http://localhost:8000/sts").then((token) => {
        const client = new OSS({
           // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
          region: 'oss-cn-hangzhou',
          accessKeyId: token.data.AccessKeyId,
          accessKeySecret: token.data.AccessKeySecret,
          stsToken: token.data.SecurityToken,
          // Specify the name of the bucket. 
          bucket: "examplebucket",
          // Refresh the temporary access credentials. 
          refreshSTSToken: async () => {
            const refreshToken = await axios.get("http://localhost:8000/sts");
            return {
              accessKeyId: refreshToken.AccessKeyId,
              accessKeySecret: refreshToken.AccessKeySecret,
              stsToken: refreshToken.SecurityToken,
            };
          },
        });
        // Use the temporary access credentials to download objects from OSS. 
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.jpg. 
        // Specify the full path of the local file. Example: D:\\example.jpg. 
        client.get('exampleobject.jpg', 'D:\\example.jpg').then((res)=>{console.log(res)}).catch(e=>console.log(e))
      });
    };
    getToken()

Use a signed URL for temporary access authorization

The following section provides examples on how to use a signed URL to authorize temporary access.

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 time during which the visitor can access the object.

Important

The signed URL generated by using the following sample code may contain a plus sign (+). In this case, you must replace + in the URL with %2B. Otherwise, the signed URL may be inaccessible.

Generate a signed URL that includes Image Processing (IMG) parameters

const OSS = require('ali-oss');
const store = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'examplebucket'
})

// Obtain the signed URL that is used to process an image named exampleobject.png. 
// Specify the full path of the object. Do not include the bucket name in the full path. 
let url = store.signatureUrl('exampleobject.png', {
  process: 'image/resize,w_200' // Configure IMG parameters used to process the image. 
});
console.log(url);

// Obtain the signed URL used to process the exampleobject.png image and specify the validity period of the URL. 
// Specify the full path of the object. Do not include the bucket name in the full path. 
 let url = store.signatureUrl('exampleobject.png', { 
  // Specify the validity period of the signed URL. By default, the validity period is 1,800 seconds. 
  expires: 3600, 
  // Configure IMG parameters used to process the image. 
  process: 'image/resize,w_200' 
});
console.log(url);

Generate a signed URL that includes the version ID

const OSS = require('ali-oss');
const client  = new OSS({  
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'examplebucket'
})
  // Generate a signed URL that includes the version ID. 
  // Specify the full path of the object. Do not include the bucket name in the full path. Example: example.png. 
  console.log(
  client.signatureUrl('example.jpg', {
    subResource: {
      // Specify the version ID of the object. 
      versionId: 'CAEQMBiBgIDW7duIqxgiIDA4OWRiYmFlZDUxMDQ3YzM4OWUyNjQzMzAzMDhj****',
    },
  })
 )

Generate a signed URL and use the signed URL to upload an object

const OSS = require("ali-oss");
const { default: axios } = require("axios");
const fs = require("fs");

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'examplebucket',
});

// Generate a signed URL for the object. 
const url = client.signatureUrl("examplefile.txt", {
  method: "PUT",
  "Content-Type": "application/x-www-form-urlencoded",
});

// Specify the full path of the local file. 
const file = fs.readFileSync("D:\\localpath\\examplefile.txt");

// Use the signed URL to upload the object. 
axios({
  url,
  method: "PUT",
  data: file,
})
  .then((r) => console.log(r))
  .catch((e) => console.log(e));

Generate a signed URL and use the signed URL to download an object

const { default: axios } = require("axios");
const fs = require("fs");

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'examplebucket'
});
// Generate a signed URL for the object. 
const url = client.signatureUrl("examplefile.txt");

// Use the signed URL to download the object to your local computer and enter the full path of the object. 
const file = "D:\\localpath\\examplefile.txt";

axios({
  url,
  method: "GET",
})
  .then((r) => {
    fs.writeFile(file, r.data, (err) => {
      if (err) {
        console.log(err);
      }
    });
  })
  .catch((e) => console.log(e));

FAQ

Can I use the POST method to generate a signed URL?

No, you cannot use the POST method to generate a signed URL. You can use only the PUT and GET methods to generate a signed URL. If you want to upload an object by using the POST method, you need to construct a POST request. For more information, see PostObject.