All Products
Search
Document Center

Object Storage Service:Authorize third-party users to download objects

Last Updated:Oct 30, 2023

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 to download objects from OSS

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 to only generate a temporary access token and send the access token to a third-party application. You do not need to provide your AccessKey pair to the third-party application. You can specify the access permissions and the validity period of the 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 validity period of temporary access credentials is in 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 sample code provides examples on how to authorize third-party users to download objects by providing the users with temporary access credentials obtained from STS by using OSS SDKs for common programming languages. For more information about how to authorize third-party users to download objects by providing the users with temporary access credentials obtained from STS by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path. 
        String objectName = "exampleobject.txt";
        String pathName = "D:\\examplefile.txt";

        // After you obtain temporary access credentials from STS, you can use the access credentials to create an OSSClient instance. 
        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {

            // Download the object to your local device. If an existing file has the same name as the downloaded object, the existing file is overwritten by the downloaded object. Otherwise, the downloaded object is saved. 
            // If you do not specify a 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(pathName));
        } 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;

// Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are configured. 
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
$securityToken = getenv("OSS_SESSION_TOKEN");
// 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. Do not include the bucket name in the full path. 
$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. The instance is used to authorize temporary access to 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;
};

// Obtain the 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 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are configured. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# 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, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Specify the full path of the object and the string that you want to download. Do not include the bucket name in the full path. 
object_name = 'exampleobject.txt'

# 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() {
    // Obtain temporary access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are configured. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Create an OSSClient instance. 
    // 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 your actual endpoint. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    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. Do not include the bucket name in the full path. 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")
}
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";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
var securityToken = Environment.GetEnvironmentVariable("OSS_SESSION_TOKEN");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. 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";

// 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 in which the object is stored, the 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;
        // Use the input stream 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 to download objects from OSS

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.

You can generate a signed URL and provide the URL to a third-party user 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 third-party user can access the OSS resources.

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.

Important

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

Use the OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation tree, choose Object Management > Objects.

  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. The following table describes the parameters. Then, click Copy Object URL.

        Parameter

        Description

        Validity Period (Seconds)

        If the access control list (ACL) of the object is private, you must specify 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 an image object or a web page object is previewed but not downloaded when the object is accessed by third-party users, generate the URL of the object by using the custom domain name mapped to the bucket.

        This parameter is available only when a custom domain name is mapped to the bucket. For more information, see Map custom domain names.

        Use HTTPS

        By default, the URL of an object is generated by using HTTPS. To use HTTP to generate a URL for the object, turn off HTTPS.

    • Obtain the URLs of multiple objects at a time

      1. Select the objects on which you want to grant third-party users the download permissions. Click Export URL List.

      2. In the Export URL List panel, configure the parameters. The following table describes the parameters.

        Parameter

        Description

        Use HTTPS

        By default, the URL of an object is generated by using HTTPS. To use HTTP to generate object URLs, turn off HTTPS.

        Validity Period (Seconds)

        If the ACL of the objects is private, you must specify 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-party users, generate the URLs of the objects by using the custom domain name mapped to the bucket.

        This parameter is available only when a custom domain name is mapped to the bucket. For more information, see Map custom domain names.

        Accelerate Endpoint

        If third-party users 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.

        This parameter is available only when transfer acceleration is enabled for the bucket. For more information, see Enable transfer acceleration.

      3. Click OK and export the URL list as a local file.

  5. Share the URL list file with third-party users for previews or downloads.

Use OSS SDKs

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

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.StorageClass;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.Date;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run code, make sure that you specified the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path. 
        String objectName = "exampleobject.txt";
        // Specify the full path of the local file to which you want to download the object. 
        String pathName = "D:\\localpath\\examplefile.txt";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
      
        // Specify request headers. 
        Map<String, String> headers = new HashMap<String, String>();
        /*// Specify the storage class of the object. 
        headers.put(OSSHeaders.STORAGE_CLASS, StorageClass.Standard.toString());
        // Specify ContentType. 
        headers.put(OSSHeaders.CONTENT_TYPE, "text/txt");*/

        // Specify user metadata. 
        Map<String, String> userMetadata = new HashMap<String, String>();
        /*userMetadata.put("key1","value1");
        userMetadata.put("key2","value2");*/

        URL signedUrl = null;
        try {
            // Specify the validity period of the signed URL. Unit: milliseconds. In this example, the validity period is set to 1 hour. 
            Date expiration = new Date(new Date().getTime() + 3600 * 1000L);

            // Generate the signed URL. 
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
            // Specify the expiration time of the request. 
            request.setExpiration(expiration);

            // Add the headers to the request. 
            request.setHeaders(headers);
            // Specify user metadata. 
            request.setUserMetadata(userMetadata);

            // Specify query parameters. 
            // Map<String, String> queryParam = new HashMap<String, String>();
            // Specify the IP address or CIDR block. 
            // queryParam.put("x-oss-ac-source-ip","192.0.2.0");
            // Specify the number of the digit 1 in the subnet mask. 
            // queryParam.put("x-oss-ac-subnet-mask","32");
            // Specify the ID of the virtual private cloud (VPC). 
            // queryParam.put("x-oss-ac-vpc-id","vpc-12345678");
            // Specify whether the request can be forwarded. 
            // queryParam.put("x-oss-ac-forward-allow","true");
            // request.setQueryParameter(queryParam);

            // Configure single-connection bandwidth throttling, such as 100 KB/s. Unit: bit/s. 
            // request.setTrafficLimit(100 * 1024 * 8);

            // Generate a signed URL that allows HTTP GET requests. 
            signedUrl = ossClient.generatePresignedUrl(request);
            // Display the signed URL. 
            System.out.println("signed url for putObject: " + signedUrl);
        } 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());
        }

        // Use the signed URL to download the object. In this example, HttpClients is used. 
        getObjectWithHttp(signedUrl, pathName, headers, userMetadata);
    }

    public static void getObjectWithHttp(URL signedUrl, String pathName, Map<String, String> headers, Map<String, String> userMetadata) throws IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            HttpGet get = new HttpGet(signedUrl.toString());

            // If you configure headers such as user metadata and storage class when a signed URL is generated, you must send these parameters to the server when you call the signed URL to download the object. If headers for the signature are inconsistent with those sent to the server, a signature error is reported. 
            for(Map.Entry header: headers.entrySet()){
                get.addHeader(header.getKey().toString(),header.getValue().toString());
            }
            for(Map.Entry meta: userMetadata.entrySet()){
                // If userMeta is used, the x-oss-meta- prefix is added to userMeta. When you use other methods to generate a signed URL for object download, the x-oss-meta- prefix is also added to userMata. 
                get.addHeader("x-oss-meta-"+meta.getKey().toString(), meta.getValue().toString());
            }

            httpClient = HttpClients.createDefault();
            response = httpClient.execute(get);

            System.out.println("Download status code:"+response.getStatusLine().getStatusCode());
            if(response.getStatusLine().getStatusCode() == 200){
                System.out.println("Download the object by using the network library");
            }
            System.out.println(response.toString());

            // Store the object in the disk. 
            saveFileToLocally(response.getEntity().getContent(), pathName);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            response.close();
            httpClient.close();
        }
    }

    public static void saveFileToLocally(InputStream inputStream, String pathName) throws IOException {
        DataInputStream in = null;
        OutputStream out = null;
        try {
            in = new DataInputStream(inputStream);
            out = new DataOutputStream(new FileOutputStream(pathName));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            in.close();
            out.close();
        }
    }
}
<?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. An 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. Do not include the bucket name in the full path. 
$object = "exampleobject.txt";
// Set the validity period of a signed URL to 3,600 seconds. 
$timeout = 3600;
// Generate a signed URL that is used to preview the object and use the custom domain name that is mapped to the bucket to access the object. 
$options= array(
    "response-content-disposition"=>"inline",);
// Generate a signed URL that is used to download the 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");               
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: "oss-cn-hangzhou",
  // 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. 
  bucket: "examplebucket",
});


// Set the Content-Disposition header 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)}`,
};
// Specify the full path of the object that you want to download. Do not include the bucket name in the full path. 
const url = client.signatureUrl("exampleobject.txt", {
  // Set the validity period to 3600. Unit: seconds. 
  expires: 3600,
  response,
});
console.log(url);
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# 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. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# 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. Do not include the bucket name in the full path. 
object_name = 'exampledir/exampleobject.txt'

# Specify headers. 
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 a signed URL that is used to download the object. The validity period of the URL is 60 seconds. 
# By default, OSS identifies forward slashes (/) in the full path of an object as escape characters when a signed URL is generated. Therefore, the signed URL cannot be used directly. 
# 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 use the generated signed URL to upload the object. 
url = bucket.sign_url('GET', object_name, 60, headers=headers, slash_safe=True)
print('the signed URL:', url)

# Use the signed URL to download the object to the local path. 
# Specify the full path of the local file. 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"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "os"
)

func HandleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}

func main() {
    // 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. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Create an OSSClient instance. 
    // 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 your actual endpoint. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    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. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
    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, the downloaded file is saved in the path. 
    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)
}
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";
// 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. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file to which you want to download the object. Example: D:\\localpath\\examplefile.txt. If the specified local file exists, the object to download replaces the file. If the specified local file does not exist, the downloaded file is saved in the path. 
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 the signed URL. 
    var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
      {
        // Set the validity period of the signed URL. Default value: 3600. Unit: seconds. 
        Expiration = DateTime.Now.AddHours(1),
    };
    var uri = client.GeneratePresignedUri(req);
}
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 information about the account that is used to access 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. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */ 
    std::string GetobjectUrlName = "exampledir/exampleobject.txt";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* 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. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    /* Specify the validity period of a signed URL. */
    std::time_t t = std::time(nullptr) + 1200;
    /* Generate the 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 network resources. */
    ShutdownSdk();
    return 0;
}