This topic describes how to authorize third-party users to download an object by providing them with temporary access credentials or a signed URL without exposing the AccessKey pair of the object owner.

Use temporary access credentials to authorize third-party users

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 You can call the AssumeRole operation or use Security Token Service (STS) SDKs for various programming languages to obtain temporary access credentials. For more information, see STS SDK overview. The temporary access credentials consist of a temporary AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. The unit of the validity period for temporary access credentials is seconds. 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

Use OSS SDKs

The following code provides examples on how to use Object Storage Service (OSS) SDKs for common programming languages to authorize third-party users to download objects by providing the users with temporary access credentials obtained from STS. For more information about how to use OSS SDKs for other programming languages to authorize third-party users to download objects by providing the users with temporary access credentials obtained from STS, see Overview.

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
String endpoint = "yourEndpoint";
// Specify the temporary AccessKey pair obtained from STS. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS. 
String securityToken = "yourSecurityToken";
// Specify the name of the bucket. Example: examplebucket. 
String bucketName = "examplebucket";
// Specify the full path of the object. Example: exampleobject.txt. The full path cannot contain the bucket name. 
String objectName = "exampleobject.txt";

// Use the temporary access credentials obtained from STS to create an OSSClient instance. 
// Create an OSSClient instance. 
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);

// Use the temporary access credentials obtained from STS to download the object and store the object as a local file. If a local file has the same name as the downloaded object, the local file is overwritten by the downloaded object. Otherwise, a file is created. 
// If you do not specify the local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File("D:\\localpath\\examplefile.txt"));

// Shut down the OSSClient instance. 
ossClient.shutdown();
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// Specify the temporary AccessKey pair obtained from STS. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS. 
$securityToken = "yourSecurityToken";
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket. 
$bucket = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name. 
$object = "exampledir/exampleobject.txt";

try {
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
    // Use the temporary access credentials obtained from STS to download the object. 
    $content = $ossClient->getObject($bucket, $object);
    var_dump($content);
} catch (OssException $e) {
    print $e->getMessage();
}
const axios = require("axios");
const OSS = require("ali-oss");

// Use the temporary access credentials to initialize an OSSClient instance on the client and then use the instance to temporarily access OSS resources. 
const getToken = async () => {
  const token = await axios.get("http://localhost:9999/sts");
  const client = new OSS({
    // Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
    region: "oss-cn-hangzhou",
    // Use STS to generate temporary access credentials. The temporary access credentials consist of a temporary AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
    accessKeyId: token.data.AccessKeyId,
    accessKeySecret: token.data.AccessKeySecret,
    stsToken: token.data.SecurityToken,
    // Specify the name of the bucket. Example: examplebucket. 
    bucket: "examplebucket",
    refreshSTSToken: async () => {
      const refreshToken = await axios.get("http://127.0.0.1:9999/sts");
      return {
        accessKeyId: refreshToken.data.AccessKeyId,
        accessKeySecret: refreshToken.data.AccessKeySecret,
        stsToken: refreshToken.data.SecurityToken,
      };
    },
  });
  return client;
};

// Query an object. 
getToken().then((client) => {
  // Use the temporary access credentials obtained from STS to download the object. 
  const url = client.signatureUrl("exampleobject.txt");
  console.log(url);
});
# -*- coding: utf-8 -*-

from aliyunsdkcore import client
from aliyunsdksts.request.v20150401 import AssumeRoleRequest
import json
import oss2

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'yourEndpoint'
# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
access_key_id = 'yourAccessKeyId'
access_key_secret = 'yourAccessKeySecret'
# Specify the name of the bucket. Example: examplebucket. 
bucket_name = 'examplebucket'
# Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path cannot contain the bucket name. 
object_name = 'exampledir/exampleobject.txt'
# To obtain the Alibaba Cloud Resource Name (ARN) information of the RAM role, log on to the RAM console. In the left-side navigation pane, choose Identities > Roles. On the Roles page, search for and click the created RAM role. In the Basic Information section of the role details page, you can view and copy the ARN information. 
# Specify the ARN information of the RAM role. Format: acs:ram::$accountID:role/$roleName. 
# $accountID specifies the Alibaba Cloud account ID. To view the Alibaba Cloud account ID, perform the following steps: Log on to the OSS console. Move the pointer over the profile picture in the upper-right corner to view and copy the account ID, or click Basic Information to view the account ID. 
# $roleName specifies the name of the RAM role. To view the RAM role name, perform the following steps: Log on to the RAM console. In the left-side navigation pane, choose Identities > Roles. On the Roles page, view the name in the Role Name column. 
role_arn = 'acs:ram::17464958********:role/ossststest'

# Create a RAM policy. 
# The policy specifies that GetObject operations can be performed only on resources in the bucket named examplebucket. 
policy_text = '{"Version": "1", "Statement": [{"Action": ["oss:GetObject"], "Effect": "Allow", "Resource": ["acs:oss:*:*:examplebucket/*"]}]}'

clt = client.AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')
req = AssumeRoleRequest.AssumeRoleRequest()

# Set the format of the returned value to JSON. 
req.set_accept_format('json')
req.set_RoleArn(role_arn)
# Specify a custom role session name to distinguish different tokens. Example: session-test. 
req.set_RoleSessionName('session-test')
req.set_Policy(policy_text)
body = clt.do_action_with_exception(req)

# Use the AccessKey pair of the RAM user to apply for a temporary access credential from STS. 
token = json.loads(oss2.to_unicode(body))

# Initialize the StsAuth instance with the authentication information in the temporary access credential. 
auth = oss2.StsAuth(token['Credentials']['AccessKeyId'],
                    token['Credentials']['AccessKeySecret'],
                    token['Credentials']['SecurityToken'])

# Initialize a bucket with the StsAuth instance. 
bucket = oss2.Bucket(auth, endpoint, bucket_name)

# Download the object from the bucket. 
read_obj = bucket.get_object(object_name)
print(read_obj.read())            
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 endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    // Specify the temporary AccessKey pair obtained from STS. 
    // Use the temporary access credentials obtained from STS to create an OSSClient instance. 
    // Create an OSSClient instance. 
    client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "yourAccessKeyId", "yourAccessKeySecret", oss.SecurityToken(securitytoken))
    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 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"
    // Use the temporary access credentials obtained from STS to download the object. 
    err = bucket.GetObjectToFile(objectName,filepath)
    fmt.Println(err)
}
using Aliyun.OSS;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "<yourEndpoint>";
// Specify the temporary AccessKey pair obtained from STS. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS. 
var securityToken = "yourSecurityToken";
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. The path cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. 
var downloadFilename = "D:\\localpath\\examplefile.txt";

// Use the temporary access credentials obtained from STS to create an OSSClient instance. 
// Create an OSSClient instance. 
var ossStsClient = new OssClient(endpoint, accessKeyId, accessKeySecret, securityToken);
try
{
    // Download the object to a stream. OssObject includes object information such as the bucket where the object is stored, object name, object metadata, and an input stream. 
    var obj = client.GetObject(bucketName, objectName);
    using (var requestStream = obj.Content)
    {
        byte[] buf = new byte[1024];
        var fs = File.Open(downloadFilename, FileMode.OpenOrCreate);
        var len = 0;
        // The input stream can be used to read and download the object content to a local file or to the memory. 
        while ((len = requestStream.Read(buf, 0, 1024)) != 0)
        {
            fs.Write(buf, 0, len);
        }
        fs.Close();
    }
    Console.WriteLine("Get object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Get object failed. {0}", ex.Message);
}

Use a signed URL to authorize third-party users

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.

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.

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.

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.

Use the OSS console

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
  3. In the left-side navigation pane, choose Files > Files.
  4. Obtain the URLs of objects.
    • Obtain the URL of a single object
      1. Click the name of the object that you want to authorize third-party users to download.
      2. In the View Details panel, configure the parameters described in the following table. Then, click Copy File URL.
        Parameter Description
        Validity Period If the ACL of the object is private, you must set a validity period for the URL of the object.

        Valid values: 60 to 32400

        Unit: seconds

        To obtain a URL that has a longer validity period, we recommend that you use ossutil or ossbrowser.

        Custom Domain Name To ensure that image objects or web page objects are previewed but not downloaded when the objects are accessed by third parties, generate the URLs of the objects by using the custom domain name mapped to the bucket.

        You can configure this parameter only when a custom domain name is mapped to the bucket. For more information, see Map custom domain names.

        HTTPS By default, the URL of an object is generated using HTTPS. To use HTTP to generate the URL of an object, turn off HTTPS.
    • Obtain the URLs of multiple objects at a time
      1. Select the objects to which you want to grant third-party users download permissions. Choose Batch Operation > Export URL List.
      2. In the Export URL List panel, configure the parameters described in the following table.
        Parameter Description
        HTTPS By default, the URLs of objects are generated using HTTPS. To use HTTP to generate object URLs, turn off HTTPS.
        Validity Period If the ACL of the objects that you want to share is private, you must set a validity period for the URLs of the objects.

        Valid values: 60 to 32400

        Unit: seconds

        To obtain URLs that have a longer validity period, we recommend that you use ossutil or ossbrowser.

        Custom Domain Name To ensure that image objects or web page objects are previewed but not downloaded when the objects are accessed by third parties, generate the URLs of the objects by using the custom domain name mapped to the bucket.

        You can configure this parameter only when a custom domain name is mapped to the bucket. For more information, see Map custom domain names.

        Accelerate Endpoint If third parties located far from your data centers need to access the shared objects, we recommend that you use the acceleration endpoint of the bucket to generate the URLs of the objects.

        You can configure this parameter only when transfer acceleration is enabled for the bucket. For more information, see Enable transfer acceleration.

      3. Click OK and then export the URL list as a local file.
  5. Share the URL list file with third parties for previews or downloads.

Use OSS SDKs

The following code provides examples on how to use OSS SDKs for common programming languages to authorize third-party users to download objects by providing the users with temporary access credentials obtained from STS. For more information about how to use OSS SDKs for other programming languages to authorize third-party users to download objects by providing the users with temporary access credentials obtained from STS, see Overview.

import com.aliyun.oss.*;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the temporary AccessKey pair obtained from STS. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the security token obtained from STS. 
        String securityToken = "yourSecurityToken";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampleobject.txt. The path cannot contain the bucket name. 
        String objectName = "exampleobject.txt";        

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // If you use STS, use the following code to initialize the instance. 
        // 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. 
        // OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
        try {
            // Specify the validity period of the signed URL. Unit: milliseconds. 
            Date expiration = new Date(new Date().getTime() + 3600 * 1000);

            // Generate the signed URL. 
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
            // Specify the expiration time of the signed URL. 
            request.setExpiration(expiration);
            Map<String, String> headers = new HashMap<String, String>();
            // To automatically download the object when the object is accessed by using a browser and specify the name of the downloaded object, set the Content-Disposition header in the configuration file to attachment. 
            headers.put("content-disposition","attachment");
            // 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. 
            // headers.put("content-disposition","inline");
            request.setHeaders(headers);
            // Generate the signed URL that allows HTTP GET requests. 
            URL signedUrl = ossClient.generatePresignedUrl(request);
            System.out.println("signed url for getObject: " + signedUrl);

            Map<String, String> customHeaders = new HashMap<String, String>();
            // Add headers to a GetObject request. 
            customHeaders.put("Range", "bytes=100-1000");
            // Use the signed URL to send a request. 
            OSSObject object = ossClient.getObject(signedUrl, customHeaders);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;

// Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS. 
$securityToken = "yourSecurityToken";
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "yourEndpoint";
// Specify the name of the bucket. 
$bucket= "examplebucket";
// Specify the full path of the object. The full path of the object cannot contain the bucket name. 
$object = "exampleobject.txt";
// Set the validity period of the signed URL to 3600. Unit: seconds. 
$timeout = 3600;
A signed URL is generated to preview an object, and the custom domain name mapped to the bucket in which the object is stored is used for access. 
$options= array(
    "response-content-disposition"=>"inline",);
// Generate a signed URL to download an object. 
/*$options = array(
    "response-content-disposition"=>"attachment",
);*/
try {
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
    $signedUrl = $ossClient->signUrl($bucket, $object, $timeout,'GET',$options);

} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");

// You can develop code to access the signed URL, or enter the URL in the address box of a browser to access the object. 
$request = new RequestCore($signedUrl);
// Set the default method to access the signed URL to GET. 
$request->set_method('GET');
$request->add_header('Content-Type', '');
$request->send_request();
$res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code());
if ($res->isOK()) {
    print(__FUNCTION__ . ": OK" . "\n");
} else {
    print(__FUNCTION__ . ": FAILED" . "\n");
};                  
const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourRegion',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. 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 name of the bucket. 
  bucket: 'examplebucket'
});

Obtain the signed URL to download the exampleobject.txt object. By default, you can preview the object to download when you use the signed URL to access the object in a browser. 
// Specify the full path of the object. The full path cannot contain the bucket name. 
const url = client.signatureUrl('exampleobject.txt');
console.log(url);

// Set Content-Disposition in exampleobject.txt 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' // Specify the name of the downloaded object. 
const response = {
  'content-disposition': `attachment; filename=${encodeURIComponent(filename)}`
}

const url = client.signatureUrl('exampleobject.txt', {
  // Set the validity period to 3600. Unit: seconds. 
  expires: 3600,
});
console.log(url);
# -*- coding: utf-8 -*-
import oss2
# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'yourEndpoint', 'examplebucket')
# Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path cannot contain the bucket name. 
object_name = 'exampledir/exampleobject.txt'

# Specify a header. 
headers = dict()
# To implement automatic download when the object is accessed by using a browser and specify the name of the downloaded object, set the Content-Disposition header in the configuration file to attachment.
# headers['content-disposition'] = 'attachment'
# 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. 
headers['content-disposition'] = 'inline'

# Generate the signed URL that is used to download the object. The validity period of the URL is 60 seconds. 
# By default, OSS identifies the forward slashes (/) in the full path of an object as escape characters when the signed URL is generated. Therefore, you cannot directly use the signed URL. 
# Set the slash_safe parameter to True. This way, OSS does not identify the forward slashes (/) in the full path of the object as escape characters. Then, you can directly use the generated signed URL. 
url = bucket.sign_url('GET', object_name, 60, headers=headers, slash_safe=True)
print('the address of the signed URL:', url)

# Use the signed URL to download the object to a local path. 
# Specify the full path of the local file to upload. Example: D:\\localpath\\examplefile.txt. 
# By default, if you set this parameter to the name of a local file such as examplefile.txt without specifying the local path, the downloaded object is saved to the local path of the project to which the sample program belongs. 
result = bucket.get_object_with_url_to_file(url, 'D:\\localpath\\examplefile.txt')
print(result.read())
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)
    }
}                    
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. 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. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the bucket name. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Specify the full path to which you want to download the object. After the object is downloaded to the specified path, the downloaded object is saved as a local file. Example: D:\\localpath\\examplefile.txt. 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. 
var downloadFilename = "D:\\localpath\\examplefile.txt";
// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    var metadata = client.GetObjectMetadata(bucketName, objectName);
    var etag = metadata.ETag;
    // Generate a signed URL. 
    var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
      {
        // Specify the validity period of the signed URL. Default value: 3600. Unit: seconds. 
        Expiration = DateTime.Now.AddHours(1),
    };
    var uri = client.GeneratePresignedUri(req);
    // Use the signed URL to download the object. 
    OssObject ossObject = client.GetObject(uri);
    using (var file = File.Open(downloadFilename, FileMode.OpenOrCreate))
    {
        using (Stream stream = ossObject.Content)
        {
            int length = 4 * 1024;
            var buf = new byte[length];
            do
            {
                length = stream.Read(buf, 0, length);
                file.Write(buf, 0, length);
            } while (length != 0);
        }
    }
    Console.WriteLine("Get object by signatrue succeeded. {0} ", uri.ToString());
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", 
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
    /* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. 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. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. */ 
    std::string GetobjectUrlName = "exampledir/exampleobject.txt";

    /* Initialize resources such as networks. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    /* Specify the validity period of a signed URL. */
    std::time_t t = std::time(nullptr) + 1200;
    /* Generate a signed URL. */
    auto genOutcome = client.GeneratePresignedUrl(BucketName, GetobjectUrlName, t, Http::Get);
    if (genOutcome.isSuccess()) {
        std::cout << "GeneratePresignedUrl success, Gen url:" << genOutcome.result().c_str() << std::endl;
    }
    else {
        /* Handle exceptions. */
        std::cout << "GeneratePresignedUrl fail" <<
        ",code:" << genOutcome.error().Code() <<
        ",message:" << genOutcome.error().Message() <<
        ",requestId:" << genOutcome.error().RequestId() << std::endl;
        ShutdownSdk();
        return -1;
    }

    /* Use the signed URL to download the object. */
    auto outcome = client.GetObjectByUrl(genOutcome.result());

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "GetObjectByUrl fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        ShutdownSdk();
        return -1;
    }

    /* Release resources such as networks. */
    ShutdownSdk();
    return 0;
}