All Products
Search
Document Center

Object Storage Service:Authorize access

Last Updated:Sep 25, 2023

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

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

  1. Build an STS server.

    // Use STS to generate temporary access credentials. The temporary access credentials consist of an AccessKey pair and a security token. 
    const { STS } = require('ali-oss');
    const express = require("express");
    const app = express();
    
    app.get('/sts', (req, res) => {
     let sts = new STS({
      // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET
    });
      // Set roleArn to the Alibaba Cloud Resource Name (ARN) of the RAM role. 
      // Set policy to a custom permission 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. 
      // sessionName specifies a custom role session name, which is used to distinguish different tokens. Example: SessionTest. 
      sts.assumeRole('acs:ram::137918634953****:role/ossram', `{
        "Version": "1",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [			
    			"oss:*"			
    		],
                "Resource": [
                    "acs:oss:*:*:examplebucket",
                    "acs:oss:*:*:examplebucket/*"
                ]
            }
        ]
    }`, '3600', '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")
    })

  2. Use STS credentials to sign a request.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>Document</title>
      </head>
      <body>
        <!-- Import the SDK file -->
        <script
          type="text/javascript"
          src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
        ></script>
        <script type="text/javascript">
          // Specify the address of your authorization server. Example: http://127.0.0.1:8000/sts. 
          fetch("yourStsServer")
            .then((resp) => resp.json())
            .then((result) => {
              const store = new OSS({
                // Specify the temporary AccessKey pair obtained from Security Token Service (STS). The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
                accessKeyId: result.AccessKeyId,
                accessKeySecret: result.AccessKeySecret,
                // Specify the security token obtained from STS. 
                stsToken: result.SecurityToken,
                // 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",
                // Specify the name of the bucket. Example: examplebucket. 
                bucket: "examplebucket",
              });
              // Generate the signed URL. 
              // Specify the full path of the object. Example: oss.png. Do not include the bucket name in the full path. 
              const url = store.signatureUrl("oss.png");
              console.log(url);
            });
        </script>
      </body>
    </html>
    

Use a signed URL for temporary access authorization

Important

To use a signed URL that contains custom parameters to access an object from a browser, make sure that the value of the Content-Type parameter contained in the URL is the same as the value of Content-Type specified in the request. Otherwise, OSS may report the SignatureDoesNotMatch error. For more information about how to set Content-Type, see How do I configure the Content-Type header?

  1. Generate a signed URL used to upload an object.

    // Generate temporary access credentials. 
    const OSS = require("ali-oss");
    const STS = require("ali-oss").STS;
    // const cors = require("cors");
    
    const stsClient = new STS({
      // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
    });
    // Specify the name of the bucket. Example: examplebucket. 
    const bucket = "examplebucket";
    // 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. 
    const region = "yourRegion";
    // Specify the ARN of the RAM role. 
    const roleArn = "acs:ram::137918634953****:role/ossram";
    const getSts = () => {
      stsClient
        .assumeRole(
          roleArn,
          `{
            "Statement": [
              {
                "Effect": "Allow",
                "Action": "*",
                "Resource": [
                  "acs:oss:*:*:examplebucket/*"
                ]
              }
            ]
          }`,
          3000 // Specify the time when the security token expires. 
        )
        .then((r) => {
          console.log("send:", r.credentials);
          const { SecurityToken, AccessKeyId, AccessKeySecret } = r.credentials;
          const client = new OSS({
            bucket,
            region,
            accessKeyId: AccessKeyId,
            accessKeySecret: AccessKeySecret,
            stsToken: SecurityToken,
            refreshSTSTokenInterval: 9000,
          });
          // Specify the name of the object to be uploaded to the bucket. 
          const url = client.asyncSignatureUrl("example.txt", {
            expires: 3600,
            method: "PUT",
            // Specify Content-Type. 
            "Content-Type": "text/plain;charset=UTF-8",
          });
          console.log("url:", url);
          // client.put("example.txt", Buffer.from("body")).then((res) => {
          //   console.log("res", res.url);
          // });
        });
    };
    getSts();
    
  2. Use the signed URL to upload the object.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>Document</title>
      </head>
      <body>
        <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
        <script>
          // Enter the signed URL generated in Step 1. 
          const url = "yourSignatureUrl";
    
          var xhr = new XMLHttpRequest();
          xhr.open("PUT", url, true);
    
          xhr.onload = function () {
            // Add code for further operations. 
          };
    
          // xhr.send(null);
          xhr.send("string");
          // xhr.send(new Blob());
          // xhr.send(new Int8Array());
          // xhr.send({ form: 'data' });
          // xhr.send(document);
        </script>
      </body>
    </html>
    

References

  • For the complete sample code that is used to authorize temporary access by using STS, visit GitHub.

  • For the complete sample code that is used to authorize temporary access by using a signed URL, visit GitHub.