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.
Note For more information about how to configure STS, see Use a temporary credential provided by STS to access OSS. You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain temporary access credentials. For more information about STS SDKs, see STS SDK overview. 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.
  • Use STS to grant a third-party user permissions to upload objects

    The following code provides an example on how to use temporary access credentials obtained from STS to grant a third-party user permissions to upload objects:

    package main
    
    import (
        "fmt"
        "github.com/aliyun/aliyun-oss-go-sdk/oss"
        "os"
    )
    
    func main() {    
        // Specify the security token obtained from STS. 
        securitytoken := "yourSecurityToken"
        // Specify the temporary AccessKey pair obtained from STS. 
        // 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. 
        // 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 bucket name. 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)
        fmt.Println(err)
    }       
  • Use STS to grant a third-party user permissions to download objects

    The following code provides an example on how to use temporary access credentials obtained from STS to grant a third-party user permissions to download objects:

    package main
    
    import (
        "fmt"
        "github.com/aliyun/aliyun-oss-go-sdk/oss"
        "os"
    )
    
    func main() {
        // Specify the security token obtained from STS. 
        securitytoken := "yourSecurityToken"
        // Specify the temporary AccessKey pair obtained from STS. 
        // 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. 
        // 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 bucket name. 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"
        // Download the object to the specified path on your local computer. If a file that has the same name already exists in the specified path, the downloaded object overwrites the file. Otherwise, a file is created. 
        // If you do not specify a path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
        filepath := "D:\\localpath\\examplefile.txt"
        // Use the temporary access credentials obtained from STS to grant the third-party user permissions to download objects. 
        err = bucket.GetObjectToFile(objectName,filepath)
        fmt.Println(err)
    }

Use a signed URL for temporary access authorization

This section provides examples on how to use a signed URL to authorize temporary access. For the complete code for using a signed URL to authorize temporary access, visit GitHub.

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

    You can add signature information to a URL and provide the URL to a third-party user for authorized access. For more information, see Add signatures to URLs.

  • Use a signed URL to upload a file

    The following code provides an example on how to use a signed URL to upload a local file named examplefile.txt from the local directory D:\\localpath to the exampledir directory of a bucket named examplebucket and store the file as an object named exampleobject.txt.

    Notice 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.
    package main
    
    import (
        "fmt"
        "os"
        "strings"
    
        "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 bucket name. Example: examplebucket. 
        bucketName := "examplebucket"
        // Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
        objectName := "exampledir/exampleobject.txt"
        // Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. 
        localFilename := "D:\\localpath\\examplefile.txt"
        
        bucket, err := client.Bucket(bucketName)
        if err != nil {
            HandleError(err)
        }
    
        // Generate a signed URL to upload the file. 
        signedURL, err := bucket.SignURL(objectName, oss.HTTPPut, 60)
        if err != nil {
            HandleError(err)
        }
    
        var val = "Go with Alibaba Cloud"
        err = bucket.PutObjectWithURL(signedURL, strings.NewReader(val))
        if err != nil {
            HandleError(err)
        }
    
        // Use the signed URL that contains custom parameters to upload the file. 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)
        }
    
        err = bucket.PutObjectFromFileWithURL(signedURL, localFilename, options...)
        if err != nil {
            HandleError(err)
        }
    }
                        
    Note For more information about the custom parameters that you can configure in a signed URL, see Manage object metadata.
  • Use a signed URL to download an object

    The following code provides an example on how to use a signed URL to download an object named exampleobject.txt from the exampledir directory of a bucket named examplebucket to a local directory named D:\\localpath. The downloaded object is stored as a local file named examplefile.txt.

    package main
    
    import (
        "fmt"
        "os"
        "io/ioutil"
    
        "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 bucket name. Example: examplebucket. 
        bucketName := "examplebucket"
        // Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
        objectName := "exampledir/exampleobject.txt"
        // Download the object to the specified path on your local computer. If a file that has the same name already exists in the specified path, the downloaded object overwrites the file. Otherwise, a file is created. 
        // If you do not specify a path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
        localDownloadedFilename := "D:\\localpath\\examplefile.txt"
        
        bucket, err := client.Bucket(bucketName)
        if err != nil {
            HandleError(err)
        }
    
        // Generate a signed URL to download the object to a stream. 
        signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, 60)
        if err != nil {
            HandleError(err)
        }
    
        body, err := bucket.GetObjectWithURL(signedURL)
        if err != nil {
            HandleError(err)
        }
        // Read the content of the object. 
        data, err := ioutil.ReadAll(body)
        body.Close()
        data = data // Use the downloaded data. 
    
        // Use the signed URL to download the object and store the object as a local file. 
        err = bucket.GetObjectToFileWithURL(signedURL, localDownloadedFilename)
        if err != nil {
            HandleError(err)
        }
    }