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.

Notice 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 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 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 a set of temporary access credentials that have a custom validity period and custom permissions to a third-party application or a RAM user managed by you. For more information about STS, see What is STS?

STS provides 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 validity period of this token.
  • The token automatically expires after the validity period. Therefore, you do not need to manually revoke the access permissions of a token.

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

  1. Obtain temporary access credentials

    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.

    You can use one of the following methods to obtain temporary access credentials.

    • Method 1

      You can call the AssumeRole operation to obtain temporary access credentials.

    • Method 2

      You can use STS SDKs to obtain temporary access credentials. For more information, see STS SDK overview.

  2. Access OSS by using temporary access credentials provided by STS
    • Upload an object by using the temporary access credentials obtained from STS
      package main
      
      import (
          "fmt"
          "github.com/aliyun/aliyun-oss-go-sdk/oss"
          "os"
      )
      
      func main() {
          // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
          client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret", oss.SecurityToken("yourSecurityToken"))
          if err != nil {
              fmt.Println("Error:", err)
              os.Exit(-1)
          }
          // Specify the name of the bucket. Example: examplebucket. 
          bucketName := "examplebucket"
          // Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
          objectName := "exampledir/exampleobject.txt"
          // Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. 
          filepath := "D:\\localpath\\examplefile.txt"
          bucket,err := client.Bucket(bucketName)
          // Use the temporary access credentials obtained from STS to grant the third-party user permissions to upload objects. 
          err = bucket.PutObjectFromFile(objectName,filepath)
          if err != nil {
              fmt.Println("Error:", err)
              os.Exit(-1)
          }
          fmt.Println("upload success")
      }
    • Download an object by using the temporary access credentials obtained from STS
      package main
      
      import (
          "fmt"
          "github.com/aliyun/aliyun-oss-go-sdk/oss"
          "os"
      )
      
      func main() {
          // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
          client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret", oss.SecurityToken("yourSecurityToken"))
          if err != nil {
              fmt.Println("Error:", err)
              os.Exit(-1)
          }
          // Specify the name of the bucket. Example: examplebucket. 
          bucketName := "examplebucket"
          // Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
          objectName := "exampledir/exampleobject.txt"
          // Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. 
          filepath := "D:\\localpath\\examplefile.txt"
          bucket,err := client.Bucket(bucketName)
          // Use the temporary access credentials obtained from STS to grant the third-party user permissions to download objects. 
          err = bucket.GetObjectToFile(objectName,filepath)
          if err != nil {
              fmt.Println("Error:", err)
              os.Exit(-1)
          }
          fmt.Println("download success")
      }

Use a signed URL for temporary access authorization

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 OSS.

Notice If you use the following code to generate a signed URL that contains the plus sign (+), you may fail to access OSS by using the URL. In this case, you must replace the plus sign (+) in the URL with %2B.

This section provides examples on how to generate a signed URL to authorize temporary access to OSS. For the complete code that is used to authorize temporary access by using a signed URL, visit GitHub.

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

  1. Generate a signed URL
    package main
    
    import (
        "fmt"
        "os"
        "github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func HandleError(err error) {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    
    func main() {
        // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
        client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret", oss.SecurityToken("yourSecurityToken"))
        if err != nil {
            HandleError(err)
        }
        // Specify the name of the bucket. Example: examplebucket. 
        bucketName := "examplebucket"
        // Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path cannot contain the bucket name. 
        objectName := "exampledir/exampleobject.txt"
        bucket, err := client.Bucket(bucketName)
        if err != nil {
            HandleError(err)
        }
        // Generate a signed URL with a specified validity period for uploading the object. In this example, the validity period of the URL is 60 seconds. 
        signedURL, err := bucket.SignURL(objectName, oss.HTTPPut, 60)
        if err != nil {
            HandleError(err)
        }
    
        // To use a signed URL that contains custom parameters to access an object from a browser, make sure that the value of the ContentType parameter contained in the URL is the same as the ContentType value specified in the request. 
        options := []oss.Option{
            oss.Meta("myprop", "mypropval"),
            oss.ContentType("text/plain"),
        }
        
        signedURL, err = bucket.SignURL(objectName, oss.HTTPPut, 60, options...)
        if err != nil {
            HandleError(err)
        }
        fmt.Printf("Sign Url:%s\n", signedURL)
    }

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

  1. Generate a signed URL
    package main
    
    import (
        "fmt"
        "github.com/aliyun/aliyun-oss-go-sdk/oss"
        "os"
    )
    
    func HandleError(err error) {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    
    func main() {
        // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
        client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret", oss.SecurityToken("yourSecurityToken"))
        if err != nil {
            HandleError(err)
        }
    
        // Specify the name of the bucket. Example: examplebucket. 
        bucketName := "examplebucket"
        // Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path cannot contain the bucket name. 
        objectName := "exampledir/exampleobject.txt"
        // Download the object to the specified path on your local computer. If the specified local file exists, the object to download replaces the file. If the specified local file does not exist, a file is created. 
        bucket, err := client.Bucket(bucketName)
        if err != nil {
            HandleError(err)
        }
    
        // Generate a signed URL with a specified validity period for downloading the object. In this example, the validity period of the URL is 60 seconds. 
        signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, 60)
        if err != nil {
            HandleError(err)
        }
        fmt.Printf("Sign Url:%s\n", signedURL)
    }